3

I have the 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 am giving a string like mxv through command line and converting that into an array and have it as MXV in 'input'. Now I want to iterate over the Hash so I can get the corresponding 'values' of the keys that I have as String in my array. For ex, for MXV , i need values = [1000, 10, 5].

How can I do that?

Niyanta
  • 473
  • 1
  • 9
  • 15
  • You would write that `'MXV'.each_char.reduce(0) { |t,c| t + hash[c] } #=> 1015 `. Mind you, there's a problem when the string is, say, `'MXIV'` (`"IV"` being `4`). – Cary Swoveland May 09 '15 at 07:02

2 Answers2

2
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 you input character does not exist in hash keys

for example:

"MXVabc".each_char.map { |i| hash[i.capitalize] } 

it will output:

=> [1000, 10, 5, nil, nil, 100]

you just need to use compact method.

"MXVabc".each_char.map { |i| hash[i.capitalize] }.compact
=> [1000, 10, 5, 100]
pangpang
  • 8,581
  • 11
  • 60
  • 96
0

I did some more research and referred to this post on stack - Ruby - getting value of hash

and solved my problem as -

  input.each do |i|
  value =  hash[i.to_sym]
    puts value
  end

Thanks to any one who took the time to look through the question.

Community
  • 1
  • 1
Niyanta
  • 473
  • 1
  • 9
  • 15