jamesvphan
jamesvphan

Reputation: 1985

Understanding puts output

I'm trying to understand the output when using puts. I know that puts really returns nil, however, I ran across something when working with Hashes.

I wanted the following block to output every key/value pair in a certain format using string interpolation, however, even though puts works as intended, I noticed that my terminal prints the entire hash as well, as you see below. I was wondering how to prevent this.

@hash.each do |key,val|
    puts "[#{key}] '#{val}'"
end 

[fish] 'aquatic animal'
[zebra] 'African land animal with stripes'
[apple] 'fruit'
=> {"fish"=>"aquatic animal", "zebra"=>"African land animal with stripes", "apple"=>"fruit"}

Upvotes: 0

Views: 33

Answers (2)

mikdiet
mikdiet

Reputation: 10038

Terminal always outputs the result of last method, each in your case. Each returns collection, so it outputs collection. You can slightly change your code to return nil, it prevents long output.

@hash.each do |key,val|
    puts "[#{key}] '#{val}'"
end; nil

Upvotes: 0

tadman
tadman

Reputation: 211720

The each method always returns the thing it was iterating over, it doesn't return the value the block provides. Presumably this is so you can chain together multiple each calls to run through something multiple times if necessary.

Keep in mind methods that take blocks are under no obligation to use whatever values those blocks return, nor are they obligated to even run the block.

As The Tin Man points out the display here is actually an artifact of the irb REPL, something that stands for "Read-Evaluate-Print-Loop". You're seeing the result of evaluating your each call, which is the return value.

Upvotes: 1

Related Questions