Reputation: 121
I have a hash like:
{"1"=>{"asset_class_id"=>"12", "ratio"=>"121"},
"2"=>{"asset_class_id"=>"22", "ratio"=>"45"},
"3"=>{"asset_class_id"=>"32", "ratio"=>"9"},
"4"=>{"asset_class_id"=>"42", "ratio"=>""}}
What I want to achieve is to get all the values of the ratio and exclude empty values something like this:
["121", "45", "9"]
Upvotes: 0
Views: 919
Reputation: 513
It's not the nicest code but you can start with this for one:
x = {"asset_class_id"=>"12", "ratio"=>"121"}
x.each do |key, value|
if key=="ratio"
puts value
end
end
Well, I've been a little late. Above solutions are better.
Upvotes: 1
Reputation: 151
hash = {"1"=>{"asset_class_id"=>"12", "ratio"=>"121"},
"2"=>{"asset_class_id"=>"22", "ratio"=>"45"},
"3"=>{"asset_class_id"=>"32", "ratio"=>"9"},
"4"=>{"asset_class_id"=>"42", "ratio"=>""}}
After you can simply call that command
Hash[hash.to_a].values.map{|v| v[:ratio].if v[:ratio].present?}
Upvotes: 0
Reputation: 6564
below code will do trick, but this ({a,b,c}
) is not valid ruby syntax.
> newarr=[]
> a.values.each {|x| newarr << x['ratio']}
=> [{"asset_class_id"=>"12", "ratio"=>"121"}, {"asset_class_id"=>"22", "ratio"=>"45"}, {"asset_class_id"=>"32", "ratio"=>"9"}, {"asset_class_id"=>"42", "ratio"=>""}]
> newarr
=> ["121", "45", "9", ""]
UPDATE
inf first version of question, empty string was also included. to skip it, you should do,
a.values.each {|x| newarr << x['ratio'] unless x['ratio'].blank? }
or,
a.values.each {|x| newarr << x['ratio'] if x['ratio'].present? }
but be aware that, above 2 lines are rails only solutions.
below is ordinary ruby.
a.values.each {|x| newarr << x['ratio'] unless x['ratio'].empty? }
Upvotes: 0
Reputation: 1613
Use this code:
arr = []
a.values.each {|e| arr << e["ratio"] if e["ratio"].present?}
puts arr
Upvotes: 0
Reputation: 2786
hash = {"1"=>{"asset_class_id"=>"12", "ratio"=>"121"},
"2"=>{"asset_class_id"=>"22", "ratio"=>"45"},
"3"=>{"asset_class_id"=>"32", "ratio"=>"9"},
"4"=>{"asset_class_id"=>"42", "ratio"=>""}}
hash.values.map{|x| x['ratio']}.reject!(&:empty?)
Upvotes: 2
Reputation: 469
> hsh = {"1"=>{"asset_class_id"=>"12", "ratio"=>"121"},
"2"=>{"asset_class_id"=>"22", "ratio"=>"45"},
"3"=>{"asset_class_id"=>"32", "ratio"=>"9"},
"4"=>{"asset_class_id"=>"42", "ratio"=>""}}
> hsh.values
=> [{"asset_class_id"=>"12", "ratio"=>"121"},
{"asset_class_id"=>"22", "ratio"=>"45"},
{"asset_class_id"=>"32", "ratio"=>"9"},
{"asset_class_id"=>"42", "ratio"=>""}]
> hsh.values.map{|h| h["ratio"]}
=> ["121", "45", "9", ""]
> hsh.values.map{|h| h["ratio"]}.reject{|v| v.empty? }
=> ["121", "45", "9"]
Upvotes: 1