Are there “rules” for Ruby syntactic sugar?

前端 未结 4 882
-上瘾入骨i
-上瘾入骨i 2021-02-10 06:22

I\'m learning the basics of Ruby (just starting out), and I came across the Hash.[] method. It was introduced with

a = [\"foo\", 1, \"bar\", 2]
=> [\"foo\", 1         


        
4条回答
  •  情话喂你
    2021-02-10 07:21

    There are a couple methods that ruby lets you call in a special way. These are the [] as you mentioned, the +, -, == and the like as someone else mentioned. Another important example are methods of the form something=(value) which can be called with object.something = value and allow you to create accessors.

    Edit:

    Fun fact 1: if you define a + method you get += for free.

    Fun fact 2: if you define a <=> you get all comparison methods, courtesy of Comparable

提交回复
热议问题