Ruby method call with character parameter without space

I saw something in a Rails application. I consider that I was expecting an error, but it works. I am confused about how this method is called with this parameter. No spaces, just two words separated by a colon:

    ree-1.8.7-2012.02 :001 > def muffin(x)
    ree-1.8.7-2012.02 :002?>   puts x.inspect
    ree-1.8.7-2012.02 :003?>   end
    => nil
    ree-1.8.7-2012.02 :004 > muffin:tuffin
    :tuffin

Also works with the line:

    ree-1.8.7-2012.02 :004 > muffin'd'
    "d"

Is this the expected and right thing?

+4
source share
2 answers

Ruby enjoys one of the most relaxed grammars in the industry. Yes, space is optional. And try muffin(:tuffin)it if you want your colleagues to see what is happening.

Next, you can write:

def muffin x

Another “because I can” example is not a good reason for something. FROM -;

+4
source

In ruby ​​methods, you can call without parentheses:

puts 'string' #returns string
puts'string'  #returns string

.

puts10 #NameError: undefined local variable or method `puts10' for main:Object
puts 10 #returns 10

, :

[1,2,3,4].count + 1 #returns 5
[1,2,3,4].count +1  #returns 1 (calls method [1,2,3,4].count with +1 as an argument)
+3

Source: https://habr.com/ru/post/1524785/


All Articles