'Iterating over array without returning the array

I'm working on a module to format print output for the console. The problem I'm running into is when I call .each on an array that I have, it returns the array in the console. I need to control what gets returned in the console.

How can I iterate through an array without having the array returned to the console?

@values.each do |value| # The end result of this is being returned, do not want.
  printf(@format,
         value[0], value[1], value[2], value[3], value[4], value[5],
         value[6]
  )
end


Solution 1:[1]

Why not create a method for your desired behavior?

def print_each_value(values, format)
  values.each do |value|
    printf(format, value[0], value[1], value[2], value[3], value[4], value[5], value[6])
  end
  nil # Here you set what you would like to return to the console.
end

print_each_value(@values, @format)

Edit: Removed annotative variable.

Solution 2:[2]

If you're only interested in the output and not the intermediate array which the interactive Ruby will always display you have two options. The first is to pass in the value you want returned:

@values.each_with_object(nil) do |value, x|
  # ...
end

Whatever you supply as the argument there will be what is returned.

The second is to return the strings and print those:

puts(
  @values.collect do |value|
    @format % values
  end.join("\n")
)

This has the advantage of dramatically simplifying your call.

As a note, if you have an array and you want to pass it through as arguments then use the splat operator:

printf(@format, *values)

Solution 3:[3]

Add ; to the end.

@values.each do |value| # The end result of this is being returned, do not want.
  printf(@format,
     value[0], value[1], value[2], value[3], value[4], value[5],
     value[6])
end;

You can see the explanation in this article.

If you chain multiple statements together in the interactive shell, only the output of the last command that was executed will be displayed to the screen

And basicaly ; in Ruby is used for chaining.

Solution 4:[4]

Try @values.cycle(1) do |value|

I wish there'd be a dedicated method for iterating for side-effects only that returns nothing tho.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 tadman
Solution 3
Solution 4 Epigene