red888 red888 - 4 months ago 5
Ruby Question

How can I enumerate a property in an array of objects, modify it, and join them in a string in ruby?

How can I enumerate a property in an array of objects, modify it, and join them in a string? I know there must be Ruby features that make this easier, but I have been having trouble understanding them.

How can I accomplish this more efficiently (less code/easier to read)?

arr = Array.new
someArrayOfObjects.map{
|obj| arr.push(obj.someProp + '-addThisStr')
}
puts arr.sort.uniq.join(', ')

#end result:
somepropA-addThisStr,somepropB-addThisStr, etc

Answer

You basically have it but you can skip the Array.new and arr.push:

result = someArrayOfObjects.map do |obj|
  obj.someProp + '-addThisStr'
end.sort.uniq.join(", ")

puts result