在Ruby中定义[方括号]方法如何工作?
我正在经历 Programming Ruby-实用的程序员指南,偶然发现了以下这段代码:
I am going through Programming Ruby - a pragmatic programmers guide and have stumbled on this piece of code:
class SongList
def [](key)
if key.kind_of?(Integer)
return @songs[key]
else
for i in 0...@songs.length
return @songs[i] if key == @songs[i].name
end
end
return nil
end
end
我不明白定义[]方法是如何工作的?
I do not understand how defining [ ] method works?
为什么键位于[]之外,但是调用该方法时却位于[]内?
Why is the key outside the [ ], but when the method is called, it is inside [ ]?
键可以不带括号吗?
我意识到有更好的方法来编写此代码,并且知道如何编写自己的方法,但是此[]方法让我感到困惑.非常感谢您的帮助.
I realize there are far better ways to write this, and know how to write my own method that works, but this [ ] method just baffles me... Any help is greatly appreciated, thanks
Ruby中的方法与许多语言不同,可以包含一些特殊字符.其中之一是数组查找语法.
Methods in ruby, unlike many languages can contain some special characters. One of which is the array lookup syntax.
如果您要实现自己的哈希类,则在其中检索哈希中的项目时,您想将其反转,则可以执行以下操作:
If you were to implement your own hash class where when retrieving an item in your hash, you wanted to reverse it, you could do the following:
class SillyHash < Hash
def [](key)
super.reverse
end
end
您可以通过以下方法调用哈希来证明这一点:
You can prove this by calling a hash with the following:
a = {:foo => "bar"}
=> {:foo=>"bar"}
a.[](:foo)
=> "bar"
a.send(:[], :foo)
=> "bar"
因此def []定义了执行操作时使用的方法.my_array["key"]
您可能对其他方法感到陌生的是:
So the def [] defined the method that is used when you do my_array["key"]
Other methods that may look strange to you are:
class SillyHash < Hash
def [](key)
super.reverse
end
def []=(key, value)
#do something
end
def some_value=(value)
#do something
end
def is_valid?(value)
#some boolean expression
end
end
只需澄清一下,[]
方法的定义与数组或哈希无关.以以下(人为)示例为例:
Just to clarify, the definition of a []
method is unrelated to arrays or hashes. Take the following (contrived) example:
class B
def []
"foo"
end
end
B.new[]
=> "foo"