我如何调用一个散列值的方法? [英] How do I call a method that is a hash value?
问题描述
以前,我问过一个聪明的方法来执行一个给定条件的方法 Ruby一个聪明的方式来执行一个条件功能。
解决方案和响应时间是伟大的,尽管如此,在实施后,有一个lambda的散列会很快变得丑陋。所以我开始尝试。
以下代码工作:
def a()
放置hello world
end
some_hash = {0 => a()}
some_hash [0]
但是,在一个类中停止工作:
class A
@a = {0 => a()}
def a()
putshello world
end
$ b def b()
@a [0]
结束
结束
d = A.new()
db()
我不明白为什么它应该停止工作,任何人都可以建议如何使它工作?$ b $该代码不起作用。解决方案
该代码不起作用。它在添加到散列时执行 a
,而不是从散列中检索(在irb中试用它)。
它在类中不起作用,因为类中没有定义 a
方法(最终定义了一个方法 a
尝试实际使用lambda表达式,例如
{0 => lambda {putshello world}}
/ p>
Previously, I asked about a clever way to execute a method on a given condition "Ruby a clever way to execute a function on a condition."
The solutions and response time was great, though, upon implementation, having a hash of lambdas gets ugly quite quickly. So I started experimenting.
The following code works:
def a()
puts "hello world"
end
some_hash = { 0 => a() }
some_hash[0]
But if I wrap this in a class it stops working:
class A
@a = { 0 => a()}
def a()
puts "hello world"
end
def b()
@a[0]
end
end
d = A.new()
d.b()
I can't see why it should stop working, can anyone suggest how to make it work?
that code doesn't work. it executes a
at the time it is added to the hash, not when it is retrieved from the hash (try it in irb).
It doesn't work in the class because there is no a
method defined on the class (you eventually define a method a
on the instance.
Try actually using lambdas like
{0 => lambda { puts "hello world" }}
instead
这篇关于我如何调用一个散列值的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!