Search code examples
arraysrubystring-interpolation

How to iteratively interpolate elements of an array into a string in Ruby?


I'm trying to do something like this:

my_array = [1,2,3]
puts "Count numbers" + my_array.each {|n| " #{n}"}

What I would like to see is "Count numbers 1 2 3". But because .each returns the array, and not what is being returned in the block, it is not possible. How can I iterate through an array and interpolate each element one by one into a string? I'm not worried about formatting white space or new line characters at the moment. However, this is going to be used in the context of error logging, and I want to give my logger just one string to print, so I can't just print each element separately.


Solution

  • This is a perfect case for Ruby's map and join functions:

    puts "Count numbers " + my_array.map{|n| n.to_s}.join(" ")
    

    The map function maps each element in the array into its string representation, and the join joins them all together, separated by spaces.

    EDIT: The map part can be left out in this specific case, where the elements are straightforwardly converted to strings. The join converts each element to a string anyway, so my_array.join(" ") is sufficient to solve this case.