【问题标题】:ruby: Using local variable in methodsruby:在方法中使用局部变量
【发布时间】:2015-04-22 08:58:45
【问题描述】:

我的主程序中有一个局部变量。现在我想给它一个方法,这样它就可以用它来工作了。 最好的方法是什么?一个实例变量@test?

【问题讨论】:

  • 通过示例从here 了解Scope

标签: ruby variables methods


【解决方案1】:

您可以将该变量作为方法参数,如下例所示:

def main_program
  my_variable = 3
  other_method(my_variable)
end

def other_method(special_variable)
  # do something with the special-variable
end

可以在Ruby programming wiki 中找到有关如何定义和调用方法的精彩阅读

【讨论】:

  • 我也可以给两个变量吗?喜欢 other_method(var1)(var2)?
  • @saigkill 是的,你可以,other_method(var1, var2)。我建议你在开始使用 Ruby 编程之前先从一些基础开始。
  • @saigkill Marek 是对的。我已经用解释红宝石方法的链接更新了我的答案。我希望这会有所帮助:)
  • 这有帮助。非常感谢
猜你喜欢
  • 2011-11-02
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
相关资源
最近更新 更多