3

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.

3 Answers 3

10
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] 
Sign up to request clarification or add additional context in comments.

8 Comments

what's -> symbol doing
Muhammad, that's the "stabby" syntax for writing lambdas, which was introduced in Ruby v1.9. As you see, I'm using it with the method Hash#default_proc=.
I like the way you turned the problem inside-out.
Quite elegant approach.
Thanks, @Gagan. If I can offer a small suggestion: work on interesting questions that are stale. This question was pretty fresh when I answered, but I often spend time on stale questions. Yesterday I posted an answer to a question that was asked in 2008 (unusually stale for me). The reason is that if a question is stale, all the obvious solutions have already been offered, so you are forced to be creative to come up with a good, original answer.
|
6

Use a Hash as a mapping and use Array#map to get a new array mapped:

mapping = {2 => 'b', 3 => 'a' }
[1,2,3,2,4,5,3,7,8].map { |x| mapping.fetch(x, x) }
=> [1, "b", "a", "b", 4, 5, "a", 7, 8]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.