Ruby - combining an array of objects by the field of objects
I have an array of objects, for example:
[ #<name: "value1", field: "field_A">, #<name: "value2", field: "field_B">, #<name: "value3", field: "field_C"> ] I want as output:
"value1 value2 value3" What am I doing now:
variable = '' array.each { |x| variable << x.name << ' ' } It is ugly and also leaves extra space at the end. I believe that Array :: join is where I want to go, but I cannot find a way to access the fields of the object from it. Is there another method similar to the connection I should use, or is there an even more sensible approach?
Any suggestions would be appreciated.
To join an Array , you must use the join method. It accepts an optional delimiter (its default value is $, , which by default is nil by default).
array.collect(&:name).join ' ' Syntax&:method is just a shorthand for { |x| x.method } { |x| x.method } .