如何在 ruby 中的方法之外使用 var?
how to use a var outside that a method in ruby?
我是 ruby 的新手,我有一个问题。
有时我有一个方法必须使用 var,但该 var 不在定义范围内..示例:
x = 1
def suma()
x+1
end
(我知道这个例子很傻,但这正是我需要的。)
需要说明的是,我正在创建一个 html 对话框,但我需要等待 rdy 才能使用它,然后再使用 Vue +js 发送数据。
我做了一个 var chk_rdy 来检查它,但我可以触摸它..
里面我有一个回调
dialog.add_action_callback('rdyimport') {|action_context, val|
}
但是我不知道该放什么来改变我的变量。
已解决!
只需将 @@ 放在 var 之前,使其成为 class var...这样您就可以从 class 中的任何地方访问它,包括方法。
这里有一个解释.. https://blog.appsignal.com/2018/10/02/ruby-magic-class-level-instance-variables.html
谢谢!
i need to wait get rdy to use it before send data with Vue +js. i made a var chk_rdy to check it, but i can touch it..
抓取实例或 class 变量会暴露对象的实现细节,这将使维护代码变得混乱。
在面向对象编程中,调用者并不确定对象是否就绪。调用者询问对象是否准备就绪。
class Foo
# foo? is the Ruby convention for methods which return true/false
# there's nothing special about the ? it is part of the method name.
def ready?
# whatever code determines the object is ready
end
end
obj = Foo.new
if obj.ready?
...its ready...
else
...it isn't...
end
这隐藏了对象内部就绪的实现细节。它确保所有准备就绪检查都以相同的方式进行。这意味着如果就绪检查的工作方式发生变化,只需更改一个地方。
您也可以随时将变量传递到您的方法中。
x = 4
def test(x)
x + 1
end
test(x) => 5
我是 ruby 的新手,我有一个问题。
有时我有一个方法必须使用 var,但该 var 不在定义范围内..示例:
x = 1
def suma()
x+1
end
(我知道这个例子很傻,但这正是我需要的。)
需要说明的是,我正在创建一个 html 对话框,但我需要等待 rdy 才能使用它,然后再使用 Vue +js 发送数据。 我做了一个 var chk_rdy 来检查它,但我可以触摸它..
里面我有一个回调
dialog.add_action_callback('rdyimport') {|action_context, val|
}
但是我不知道该放什么来改变我的变量。
已解决!
只需将 @@ 放在 var 之前,使其成为 class var...这样您就可以从 class 中的任何地方访问它,包括方法。
这里有一个解释.. https://blog.appsignal.com/2018/10/02/ruby-magic-class-level-instance-variables.html
谢谢!
i need to wait get rdy to use it before send data with Vue +js. i made a var chk_rdy to check it, but i can touch it..
抓取实例或 class 变量会暴露对象的实现细节,这将使维护代码变得混乱。
在面向对象编程中,调用者并不确定对象是否就绪。调用者询问对象是否准备就绪。
class Foo
# foo? is the Ruby convention for methods which return true/false
# there's nothing special about the ? it is part of the method name.
def ready?
# whatever code determines the object is ready
end
end
obj = Foo.new
if obj.ready?
...its ready...
else
...it isn't...
end
这隐藏了对象内部就绪的实现细节。它确保所有准备就绪检查都以相同的方式进行。这意味着如果就绪检查的工作方式发生变化,只需更改一个地方。
您也可以随时将变量传递到您的方法中。
x = 4
def test(x)
x + 1
end
test(x) => 5