Reputation: 13
I have the below array of hashes
z = {"RANGE"=>[{"10-50"=>"5"}, {"50-100"=>"15"}, {"100-150"=>"25"}]}
How can I get output as 10
Upvotes: 1
Views: 1481
Reputation: 44581
You can try the following:
z["RANGE"].map(&:keys).flatten.map(&:to_i).min
#=> 10
Upvotes: 2
Reputation: 110675
z["RANGE"].map { |h| h.first.first.to_i }.min #=> 10
Alternatively, to avoid the construction of a temporary array:
z["RANGE"].min_by { |h| h.first.first.to_i }.first.first.to_i #=> 10
Note: "10-50".to_i #=> 10
.
Postscript: considering how often one sees hashes having at most one key-value pair, perhaps we could use some Hash
methods for working with them specifically. For example:
class Hash
def only_key
raise StandardError, "Hash has > 1 keys" if size > 1
first.first
end
def only_value
raise StandardError, "Hash has > 1 keys" if size > 1
first.last
end
end
We could then write:
z["RANGE"].map { |h| h.only_key.to_i }.min #=> 10
and if we wanted the smallest value:
z["RANGE"].map { |h| h.only_value.to_i }.min #=> 5
Upvotes: 2