Iterating over hashes to retrieve values that match an array
I have a code -
class Conversion
hash ={'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000}
puts "enter the string"
input = gets.chomp.upcase.split(//)
result = 0
hash.each do | key, value |
case key
when 'M'
result = result + value
when 'D'
result = result + value
when 'C'
result = result + value
when 'L'
result = result + value
when 'X'
result = result + value
when 'V'
result = result + value
when 'I'
result = result + value
end
end
puts result
end
c= Conversion.new
I give a string like mxv via command line and convert it to an array and use it as MXV in "input". Now I want to iterate over the hash to get the corresponding "values" of the keys that I have as a String in my array. For example, for MXV I need values = [1000, 10, 5].
How can i do this?
+3
source to share
2 answers
arr = []
"MXV".each_char do |i|
arr << hash[i.capitalize]
end
arr = [1000, 10, 5]
or
"MXV".each_char.map { |i| hash[i.capitalize] }
If the entered character does not exist in the hash keys
eg:
"MXVabc".each_char.map { |i| hash[i.capitalize] }
it will output:
=> [1000, 10, 5, nil, nil, 100]
you just need to use the method compact
.
"MXVabc".each_char.map { |i| hash[i.capitalize] }.compact
=> [1000, 10, 5, 100]
+2
source to share
I did some more research and referenced this post on the stack - Ruby - getting hash value
and solved my problem as -
input.each do |i|
value = hash[i.to_sym]
puts value
end
Thanks for taking the time to review the question.
0
source to share