Are there "rules" for Ruby syntactic sugar?

I am learning the basics of Ruby (just getting started) and I came across a method Hash.[]. It was introduced using

a = ["foo", 1, "bar", 2]
=> ["foo", 1, "bar", 2]
Hash[*a]
=> {"foo"=>1, "bar"=>2}

After a little thought, I realized that it is Hash[*a]equivalent to Hash.[](*a)or Hash.[] *a. My question is why this is the case. What allows you to put *ain square brackets, and is there any rule for where and when you can still use it?

Edit: My wording causes some confusion. I am not asking about array expansion. I understand. My question is basically: if []is the name of the method, why is everything okay to put arguments inside the brackets? It seems almost, but not quite, for example, saying that if you have a method Foo.doodand you wanted to pass a string to it "hey", then you could write Foo.do"hey"od.

+5
source share
4 answers

, Ruby . [], , +, -, == , - . something=(value), object.something = value .

Edit:

Fun fact 1: +, += .

2: <=>, , Comparable

+3

Hash["a", "b", "c", "d"] Hash.[]("a", "b", "c", "d"). Ruby - . 5 + 5 5.+(5).

a = ["a", "b", "c", "d"] Hash[*a] Hash["a", "b", "c", "d"], , , Hash.[]("a", "b", "c", "d"). , foo(*a) foo("a", "b", "c", "d") .


, , *a . - . "" , *a .

+4

, Ruby parse.y YARV Ruby.

+2

*<Array> ruby ​​ , .

:

def test(*argv)
  p argv
end

a = [1,2,3]
test(a) #-> [[1, 2, 3]]
test(*a) #-> [1, 2, 3]    

test(a) a .

test(*a) a .


a = ["foo", 1, "bar", 2]
Hash[*a]

looks like

Hash["foo", 1, "bar", 2]

Hash[*a] will be

Hash[["foo", 1, "bar", 2]]
0
source

All Articles