1

I have an array in Ruby, like ["dog", "cat", bat"]. How can I get an array in which each element is passed to a particular method? For example, if the method reverses the input string, then I expect to get ["god", "tac", "tab"]. I know it's easy to iterate over the elements, pass them into the method, and put the results into an array. But is there a shorter way?

EDIT: I'd also not like to modify the original array.

1
  • 1
    map will not modify original array Commented Nov 24, 2012 at 21:07

1 Answer 1

6
["dog", "cat", "bat"].map { |word| word.reverse }

or

["dog", "cat", "bat"].map &:reverse
Sign up to request clarification or add additional context in comments.

2 Comments

No, it's a standard part of ruby syntax. I just tried it in irb without any gems and it worked.
It's available in any version of Ruby that has Symbol#to_proc. I believe it was added in 1.8.7.

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.