Rewriting the "best" code

I am using Ruby 1.9, and I would like to know if there is a “better” way to write the following code.

  array_one = []
  array_two = []
  some_array.each { |value|
    array_one << value.id
    array_two << value.name
  }

I don’t like to “initialize array_oneand array_twolike in the above example, and then add those value.idand value.name. This is because mainly for better understanding and reading the code in my application.

I would like to provide the same functionality, but with "better" coding. Is it possible?

+5
source share
3 answers

, , fold (, , ), . Ruby , inject.

:

array_one, array_two = some_array.
  inject([[], []]) {|(array_one, array_two), value|
    [array_one << value.id, array_two << value.name]
}

, , "" . , , fold, , , . -, , , .

( , , fold, Ruby , .)

, , fold , fold ( , fold). , , map:

array_one, array_two = some_array.map(&:id), some_array.map(&:value)

, some_array . , , , , .

+5

Array # collect:

array_one = some_array.collect { |value| value.id }
array_two = some_array.collect { |value| value.name }

W , .

+1

transpose n-, , n-:

array_one, array_two = some_array.map {|value| [value.id, value.name]}.transpose

RDoc, .

+1

All Articles