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.
array.map(&:name).join(" ")
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 }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With