在 Ruby 中定义 [方括号] 方法是如何工作的? [英] How does defining [square bracket] method in Ruby work?

查看:19
本文介绍了在 Ruby 中定义 [方括号] 方法是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 ProgrammingRuby - a pragmatic 程序员指南 并偶然发现了这段代码:

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?

为什么key在[]外面,而调用方法的时候却在[]里面?

Why is the key outside the [ ], but when the method is called, it is inside [ ]?

key 可以不带括号吗?

Can key be without parenthesis?

我意识到有更好的方法来编写这个,并且知道如何编写我自己的有效方法,但是这个 [ ] 方法只是让我感到困惑......非常感谢任何帮助,谢谢

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" 

这篇关于在 Ruby 中定义 [方括号] 方法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆