2017-02-05 2 views
-1

Warum kann ich mit Ruby keine Zufallsvariable übergeben? Ich habe verschiedene Kombinationen ausprobiert, z. B. das Entfernen von Zahlen.Ruby-Rand-Funktion in Methode

money= rand(100) 

def paycheck(money) 
    "Lets make this amount, #{money} today" 
end 

puts paycheck("100") 
puts paycheck("200") 
puts paycheck("500") 
+0

Wo versuchen Sie eine Zufallsvariable zu übergeben? – trueinViso

+0

Sie können verwirrt sein über die Bedeutung von "Geld" in verschiedenen Kontexten. Innerhalb der "Gehaltsscheck" -Methode ist "Geld" eine neue Variable, die für diese Methode privat ist und nichts mit der Variablen "Geld" zu tun hat, die Sie außerhalb der Methode deklariert haben. Dies wird Shadowing https://en.wikipedia.org/wiki/Variable_shadowing genannt –

Antwort

1

Sie können:

money= rand(100) 
puts paycheck(money) 

Wenn Sie definieren Ihre Methode paycheck(money) - es ist anders Variable money, dass der eine auf dieser Linie: money = rand(100)

1

Sie können etwas tun:

def paycheck(limit) 
    money = rand(limit.to_i) 
    "Lets make this amount, #{money} today" 
end 

puts paycheck("100") #=> Lets make this amount, 14 today 
puts paycheck("200") #=> Lets make this amount, 111 today 
puts paycheck("500") #=> Lets make this amount, 119 today