Search code examples
rubyenumerable

map method with mutated iterator


I have an array of objects I want to iterate through with map-

object_array.map {|o| o.dostuff }

But I want o iterator to be a string representation of the object, so I have to do something like this-

object_array.map do |o|
  o = o.to_s
  o.dostringstuff
end

Is there any way to do it in one line? (intrepreter doesn't accept this)

object_array.map {|o.to_s| o.dostringstuff }

Solution

  • Why not chain maps, especially with a shorthand syntax via Symbol#to_proc?

    object_array.map(&:to_s).map(&:dostringstuff)