0

I have an array short_code[] that contains an array of short product identifiers such as ["11111", "2222", "33333"]

I want to create a copy of the array that contains the corresponding 'long code' data:

long_code[i] = my_lookup_long_code(short_code[i])

While simple iteration is easy, I'm wondering, as a relative ruby newbie, what is the 'ruby way' to create an array which is a simply method() applied on every element in the original array?

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
jpw
  • 18,697
  • 25
  • 111
  • 187

1 Answers1

6

You can use the map command, which will return a new array with the results of your code block:

long_code = short_code.map{ |code| my_lookup_long_code(code) }
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • This could be written as short_code.map(&method(:my_lookup_long_code)) IIRC. – Andrew Grimm Aug 23 '11 at 22:13
  • @Jorg: Is it reminding you of http://stackoverflow.com/questions/6962883/how-to-unflatten-a-ruby-array/6963422#6963422 , or http://stackoverflow.com/questions/6976629/is-the-methodmethod-name-idiom-bad-for-perfomance-in-ruby , or something else? – Andrew Grimm Aug 24 '11 at 01:24
  • @Andrew Grimm: All of the above :-) – Jörg W Mittag Aug 24 '11 at 01:26