是否有“规则"?对于 Ruby 语法糖? [英] Are there "rules" for Ruby syntactic sugar?
问题描述
我正在学习 Ruby 的基础知识(刚刚开始),并且遇到了 Hash.[]
方法.它被引入
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, "bar", 2]
Hash[*a]
=> {"foo"=>1, "bar"=>2}
稍加思考,我发现 Hash[*a]
等价于 Hash.[](*a)
或 Hash.[]*a
.我的问题是为什么会这样.是什么让您将 *a
放在方括号内,是否有某种规则可以在何时何地使用它"?
With a little thought, I figured out that Hash[*a]
is equivalent to Hash.[](*a)
or Hash.[] *a
. My question is why that's the case. What is it that lets you put the *a
inside the square brackets, and is there some kind of rule for where and when else "it" can be used?
我的措辞似乎引起了一些混乱.我不是在问阵列扩展.我明白了.我的问题基本上是:如果 []
是一个方法名称,为什么可以将参数放在括号内?看起来几乎——但并不完全——就像说如果你有一个方法 Foo.dood
,并且你想将字符串 "hey"
传递给它,那么你可以写Foo.do"hey"od
.
My wording seems to be causing some confusion. I'm not asking about the array expansion. I get that. My question is basically: if []
is a method name, why is it okay to put arguments inside the brackets? It seems almost--but not quite--like saying that if you have a method Foo.dood
, and you wanted to pass the string "hey"
to it, then you could write Foo.do"hey"od
.
推荐答案
ruby 有几个方法可以让你以一种特殊的方式调用.这些是您提到的 []
、+
、-
、==
等其他人提及.另一个重要的例子是 something=(value)
形式的方法,它可以用 object.something = value
调用并允许你创建访问器.
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.
有趣的事实 1:如果您定义一个 +
方法,您将免费获得 +=
.
Fun fact 1: if you define a +
method you get +=
for free.
有趣的事实 2:如果您定义了 <=>
,您将获得所有比较方法,由 比较
Fun fact 2: if you define a <=>
you get all comparison methods, courtesy of Comparable
这篇关于是否有“规则"?对于 Ruby 语法糖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!