SupremeA SupremeA - 5 months ago 7
Ruby Question

Method keeps returning nil

I have an array of arrays that looks like the following

transactions = [{"id"=>"83Z...",
"date"=>"2016-05-24",
"amount"=>6.22,
"name"=>"DD/BR #346737 Q35"},
{"id"=>"jzEo...",
"date"=>"2016-05-24",
"amount"=>8.37,
"name"=>"Yl Statedivision Inc"}
]


I am running the method below to get an array of just the names (no repeat names) with all numbers removed from the name.

In console it works fine but when I try and run it on my actual app the filtered_names comes back as an array of nil's and causes the method to fail. I cannot figure out what is wrong.

def transaction_names
short_list = self.transactions.find_all { |t| Date.parse(t["date"]) >= 90.days.ago.to_date}
filtered_names = short_list.map { |trans| trans[:name] }
short_names = filtered_names.map { |name| name.gsub(/\d\s?/, "") }.uniq
self.trans_names = short_names
save
end


This should return

trans_names = ["DD/BR","Yl Statedivision Inc"]

Answer

Your original hash has keys that are strings, but you use a symbol to fetch the name. Just change this line

filtered_names = short_list.map { |trans| trans[:name] }

to

filtered_names = short_list.map { |trans| trans['name'] }