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

后端 未结 4 577
不思量自难忘°
不思量自难忘° 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:49

    the square brackets are the method name like Array#size you have Array#[] as a method and you can even use it like any other method:

    array = [ 'a', 'b', 'c']
    array.[](0) #=> 'a'
    array.[] 1  #=> 'b'
    array[2]    #=> 'c'
    

    the last one is something like syntactic sugar and does exactly the same as the first one. The Array#+ work similar:

    array1 = [ 'a', 'b' ]
    array2 = [ 'c', 'd' ]
    array1.+(array2) #=> [ 'a', 'b', 'c', 'd' ]
    array1.+ array2  #=> [ 'a', 'b', 'c', 'd' ]
    array1 + array2  #=> [ 'a', 'b', 'c', 'd' ]
    

    You can even add numbers like this:

    1.+(1) #=> 2
    1.+ 1  #=> 2
    1 + 1  #=> 2
    

    the same works with /, *, - and many more.

提交回复
热议问题