I have an array like this:
[1,2,3,2,4,5,3,7,8]
I want to map them to other elements 2=> 'b', 3=>'a'
[1,'b','a','b',4,5,'a',7,8]
What are some strategies to do it.
arr = [1,2,3,2,4,5,3,7,8]
h = { 2=>'b', 3=>'a' }
h.default_proc = ->(_,k) { k }
h.values_at(*arr)
#=> [1, "b", "a", "b", 4, 5, "a", 7, 8]
Here's another possible solution, similar to @falsetru's answer:
mapping = Hash.new {|_, v| v }.merge(2 => 'b', 3 => 'a')
[1, 2, 3, 2, 4, 5, 3, 7, 8].map(&mapping.method(:[]))
# => [1, 'b', 'a', 'b', 4, 5, 'a', 7, 8]
In Feature #11262 – Make more objects behave like "Functions" on the Ruby issue tracker, I suggested that Hashes should behave like functions from keys to values, i.e. they should implement call and to_proc, which would allow you to pass the mapping directly as the transformation function to map:
[1, 2, 3, 2, 4, 5, 3, 7, 8].map(&mapping)
# => [1, 'b', 'a', 'b', 4, 5, 'a', 7, 8]
Until my suggestion gets implemented (which is probably "never", considering that nobody has even looked at it in two months), you need this monkey patch to get it to work:
module HashAsFunction
refine Hash do
alias_method :call, :[]
def to_proc
method(:call).to_proc
end
end
end
using HashAsFunction