John Smith
John Smith

Reputation: 6259

Replace specific Elements in Ruby

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?

Upvotes: 2

Views: 110

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You could use Module#const_get, like so:

M,X,C,Y = '1','2','5','1'
arr = ['M','X','C','Y','C']

arr.map { |e| Object.const_get(e) }
  #=> ["1", "2", "5", "1", "5"]

(Not advocating, just saying.)

Upvotes: 0

amnn
amnn

Reputation: 3716

If the array is always a string, you can do the following:

arr = %W(M X C Y C)
arr.join.tr("MYXC", "1125").split("")

Upvotes: 1

falsetru
falsetru

Reputation: 369074

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"]

Upvotes: 8

Stefan
Stefan

Reputation: 114178

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.

Upvotes: 2

Related Questions