【问题标题】:Assigning return value to variable in Ruby in Learn Ruby the Hard Way, exercise 21在 Ruby the Hard Way 中为 Ruby 中的变量分配返回值,练习 21
【发布时间】:2013-10-19 12:51:30
【问题描述】:

在 Zed Shaw 的 Learn Ruby the Hard Way 中,练习 21:

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

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

这打印年龄:35。

我在之前的练习(ex20)中尝试过这样做:

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

current_file = File.open(input_file)

sausage = print_all(current_file)

puts "Sausage: #{sausage}"

但是当我运行它时,即使我将文件指针移回 0,#{sausage} 也不会打印:

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}"

我将 add(a, b) 方法的返回值赋值给 age,为什么我不能对 print_all(current_file) 做同样的事情?

【问题讨论】:

    标签: ruby return-value variable-assignment learn-ruby-the-hard-way


    【解决方案1】:
    def print_all(f)
        puts f.read()
    end
    

    print_all的返回值是puts f.read()的返回值,是puts的返回值,不是f.read()的返回值。 puts 总是返回 nil。因此,print_all 总是返回 nil

    也许你打算:

    def print_all(f)
        f.read()
    end
    

    或者如果你需要在你的函数/方法中打印它:

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

    【讨论】:

    • def print_all(f) f.read() end 的'返回值'是不是'读取'input_file的动作?
    • @user2835005,返回值不是读取的“动作”,而是读取输入文件的“结果”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 2015-06-01
    相关资源
    最近更新 更多