How to get the maximum value from hash

Viewed 66

I want to get the maximum value from the hash but i keep getting the first one

Crypto_name = ["Bitcoin", "Ethereum", "Project-x", "Fake"]
Crypto_price = ["$5500.6", "$538.9", "$0.25", "$46000.09"]
$crypto = Crypto_name.zip(Crypto_price).to_h

def largest_hash_key
  puts $crypto.max_by{|a,b| b.to_i}
end

largest_hash_key
2 Answers

As per the format of each string within crypto_price, you'd need to remove any non-digit character, with those 4 elements, $ is the one you don't need.

max can help you:

$crypto.max { |value| value.last.delete('$').to_f }
# "$46000.09"

By removing the $ you get a "convertible" to float number, which you can then compare.

I blindly assume that "$" is the only one character that's not needed among them. But it won't be always this way.

Perhaps

$crypto.max_by{|a,b| b.tr('^0-9''.','').to_f}

I think this works with any symbols and in any order.

Related