Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Join array of objects by an objects field

Tags:

ruby

I have an array of objects, like so:

[
    #<name: "value1", field: "field_A">,
    #<name: "value2", field: "field_B">,
    #<name: "value3", field: "field_C">
]

I want as output:

"value1 value2 value3"

What I am currently doing:

variable = ''
array.each { |x| variable << x.name << ' ' }

This is ugly, and also leaves an extra space on the end. I thing Array::join is where I am looking to go, but I can't find a way to access the object fields from it. Is there another method similar to join that I should be using, or is there another more sensible approach?

Any suggestions would be appreciated.

like image 459
Jimmy Pitts Avatar asked Jan 27 '13 01:01

Jimmy Pitts


2 Answers

array.map(&:name).join(" ")
like image 113
sawa Avatar answered Sep 17 '22 15:09

sawa


In order to join an Array you should use the join method. It takes an optional separator (its default value is $, which in turn nil by default).

array.collect(&:name).join ' '

&:method syntax is just a shorthand for { |x| x.method }.

like image 26
nameless Avatar answered Sep 19 '22 15:09

nameless