It is impossible to understand the difference between `puts {}. Class` and `puts ({}. Class)`

Since the anonymous block and the hash block look pretty much the same. I played with him. And I do, I came to some serious observations, as shown below:

{}.class
#=> Hash

Nice cool. an empty block is considered Hash.

print{}.class
#=> NilClass
puts {}.class

#=> NilClass

Now, why does the above code show the same thing as NilClass, but the code below shows again Hash?

puts ({}.class)
#Hash
#=> nil
print({}.class)
#Hash=> nil

Can someone help me here to understand what is happening above?

I totally disagree with @Lindydancer's point

As you explain the lines below:

print {}.class
#NilClass
print [].class
#Array=> nil
print (1..2).class
#Range=> nil

Why not the same with below print [].classand print (1..2).class?

EDIT

When ambiguity occurs when local variableand is called method, Ruby displays the error message described below:

name
#NameError: undefined local variable or method `name' for main:Object
#        from (irb):1
#        from C:/Ruby193/bin/irb:12:in `<main>'

{} ( empty code block Hash). IRB , a empty block Hash. , IRB print {}.class {}.class?

+5
3

{} , print, [] .

print {}.class                            # => NilClass
print do;end.class                        # => NilClass
+3

ruby ​​ print{}.class (print{}).class. print, -, a nil, class #NilClass.

EDIT: ​​ , print{} , , print , . , {} [] (1..2) ( , do ... end, ).

+6

Ruby, . , , , {} , , - .

, , .


:

Parens (),

print(1..5).class => NilClass
print (1..5).class => Range <returns nil>

[] :[]

print[].class => NoMethodError: undefined method `[]' for nil:NilClass
print([].class) => Array <returns nil>

Asterisk *

1 * 5 => 5
[*1..5] => [1, 2, 3, 4, 5]

Ampersand is &used for → proc symbol or logical and

0 & 1 => 0
[1, 2, 3].map(&:to_s) => ["1", "2", "3"]

Or in your case, the brackets used to close the blocks or for the hash

... hope it makes sense now ...
+1
source

All Articles