How does defining [square bracket] method in Ruby work?

后端 未结 4 575
不思量自难忘°
不思量自难忘° 2020-12-12 21:52

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?         


        
4条回答
  •  再見小時候
    2020-12-12 22:47

    It's an operator overloader, it overrides or supplements the behavior of a method inside a class you have defined, or a class the behavior of which you are modifying. You can do it to other operators different from []. In this case you are modifying the behavior of [] when it is called on any instances of class SongList.

    If you have songlist = SongList.new and then you do songlist["foobar"] then your custom def will come into operation and will assume that "foobar" is to be passed as the parameter (key) and it will do to "foobar" whatever the method says should be done to key.

    Try

    class Overruler
        def [] (input)
              if input.instance_of?(String)
                puts "string"
              else
                puts "not string"
              end
         end
    end
    foo = Overruler.new
    foo["bar"].inspect
    foo[1].inspect
    

提交回复
热议问题