hummmingbear
hummmingbear

Reputation: 2384

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

Upvotes: 2

Views: 1985

Answers (4)

Epigene
Epigene

Reputation: 3908

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

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

Upvotes: 0

tadman
tadman

Reputation: 211560

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)

Upvotes: 2

BenNapp
BenNapp

Reputation: 261

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.

Upvotes: 3

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3043

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.

Upvotes: 1

Related Questions