Search code examples
rubyreturn-valuevariable-assignmentlearn-ruby-the-hard-way

Assigning return value to variable in Ruby in Learn Ruby the Hard Way, exercise 21


In Zed Shaw's Learn Ruby the Hard Way, exercise 21:

def add(a, b)
  puts "ADDING #{a} + #{b}"
  a + b
end

age = add(30, 5)  
puts "Age: #{age}"

This prints Age: 35.

I tried doing this with the previous exercise (ex20):

def print_all(f)
    puts f.read()
end

current_file = File.open(input_file)

sausage = print_all(current_file)

puts "Sausage: #{sausage}"

But when I run it, #{sausage} does not print, even after I move the file pointer back to 0:

def print_all(f)
    puts f.read()
end

def rewind(f)
  f.seek(0, IO::SEEK_SET)
end

current_file = File.open(input_file)

sausage = print_all(current_file)

rewind(current_file)

puts "Sausage: #{sausage}"

I assigned the return value from method add(a, b) to age, why can't I do the same with print_all(current_file)?


Solution

  • def print_all(f)
        puts f.read()
    end
    

    The return value of print_all is the return value of puts f.read(), which is the return value of puts, not the return value of f.read(). puts always returns nil. Therefore, print_all always returns nil.

    Perhaps you intended:

    def print_all(f)
        f.read()
    end
    

    Or if you need to print it in your function/method:

    def print_all(f)
        foo = f.read()
        puts foo
        foo
    end