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.
CodePudding user response:
There should be no reason to pass a block at all. You should be able to simply use the join method like so:
puts "Count numbers " my_array.join(" ")
#=> "Count numbers 1 2 3"
...or, interestingly enough, you can alternatively use the splat operator to do nearly the same thing:
puts "Count numbers " my_array*(" ")
#=> "Count numbers 1 2 3"
NOTE: I included the splat operator option mostly just as a curious alternative. I'm not sure it really has any benefit over the join method unless perhaps you're trying to make your code as cryptic as possible. You never know though. Its always nice to know what methods are available.
CodePudding user response:
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.
