[英]Are there methods for enabling Hash-style look-ups in custom classes?
I'm pretty sure there are some methods I can implement in my classes to make look-ups like this possible: 我很确定我可以在我的类中实现一些方法来使这样的查找成为可能:
foo = MyClass.new
foo["bar"] = 123
But what are they? 但他们是什么?
you can always define your own []
and []=
methods (google: "operator overloading") eg: 您可以随时定义自己的[]
和[]=
方法(谷歌:“运算符重载”),例如:
class MyClass
def [](key)
# ...
end
def []=(key, value)
# ...
end
end
Here are some examples: 这里有些例子:
http://net.tutsplus.com/tutorials/ruby/ruby-for-newbies-operators-and-their-methods/ http://net.tutsplus.com/tutorials/ruby/ruby-for-newbies-operators-and-their-methods/
https://www.ruby-forum.com/topic/4067570 https://www.ruby-forum.com/topic/4067570
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.