【发布时间】: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