Lets say i have a array in ruby for example:
arr = ['M','X','C','Y','C']
How can i replace the elements with the value 'M' and 'Y' with '1'
and replace 'X' with '2'
and last 'C' with '5'
So that at the end my array is transformed to:
['1','2','5','1','5']
I know there are several ways i tried for example a case-loop:
arr.map { |i| case i
when ['X'].include? i then '2'
when ['M','Y'].include? i then '1'
when ['C'].include? i then '5'
end }
But that somehow gave me this error:
syntax error, unexpected keyword_end, expecting '}'
... end }
What did i wrong or what could i use instead?
Using a hash and Array#map!:
mapping = {'M' => '1', 'Y' => '1', 'X' => '2', 'C' => '5'}
arr = ['M','X','C','Y','C']
arr.map! { |c| mapping[c] }
# => ["1", "2", "5", "1", "5"]
UPDATE
As Stefan suggested, you can also use Hash#values_at:
arr = ['M','X','C','Y','C']
mapping = {'M' => '1', 'Y' => '1', 'X' => '2', 'C' => '5'}
mapping.values_at(*arr)
# => ["1", "2", "5", "1", "5"]
Regarding your error, you would use a case statement like this:
arr = ['M','X','C','Y','C']
arr.map { |i|
case i
when 'X' then '2'
when 'M', 'Y' then '1'
when 'C' then '5'
end
}
#=> ["1", "2", "5", "1", "5"]
The block is called for each element and the element is passed into the block as i.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With