我試圖理解為什么這段代碼重復了 age 和 name 方法 2 次。當我運行代碼時,它會詢問年齡和姓名,但是,它會再次詢問姓名和年齡。我不確定我到底做錯了什么?它只意味著要問 1 次。
我嘗試了全域變數并且它有效但我真的不想使用全域變數
require 'date'
def get_age()
puts("Enter your age in years: ")
age = gets.to_i()
return age
end
def get_string()
puts("Enter your name: ")
s = gets.chomp()
return s
end
def print_year_born(get_age)
year_born = Date.today.year - get_age
puts(get_string "\sYou were born in: " year_born.to_s)
end
def main()
get_age()
get_string()
print_year_born(get_age)
end
main()
我錯過了什么?
uj5u.com熱心網友回復:
它被呼叫兩次,因為你呼叫了它兩次。在 的第 1 行main,您呼叫get_age()并丟棄它回傳的值。然后在第 3 行呼叫print_year_born(get_age)whichget_age再次呼叫,但這次將回傳的值傳遞給print_year_born。
您似乎對方法的作業原理有些困惑。每次鍵入get_age時,都會呼叫該方法。您不必在第 1 行和第 2 行自行呼叫這些方法,那些裸呼叫 ( get_age()/ get_string()) 是完全多余的。他們呼叫方法,但絕對不對回傳的值做任何事情。
目前尚不清楚您認為 main serve 中的前兩行的目的是什么,但您應該洗掉它們:
def main()
get_age() # Wrong: call get_age and ignore return value. Why?
get_string() # Wrong: call get_string and ignore return value. Why?
# Correct: call get_age and use the return value as an argument to print_year_born
print_year_born(get_age)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536891.html
標籤:红宝石
上一篇:引數名稱的字串
