

Ruby Asterisk 和 Ampersand
source link: https://mednoter.com/Ruby-ampersand-asterisk.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Ruby Asterisk 和 Ampersand
Ruby 两个符号 * 和 & 经常帮我搞得晕头转向,今天梳理了他们的两个两个最主要的使用场景:
- 调用方法时
- 定义方法时
Asterisk *
在调用方法时,若在参数中加上 *,表示:先拆分数组,再调用方法
a = ["Jesus", "Loves", "U"]
# 以下两种效果一致
p(*a)
p(a[0], a[1], a[2])
在定义方法时,若在参数中加上*, 则表示: 方法内部会把所有的参数转化为一个数组。
def say_hello(*a)
puts a
puts a.class
end
c, d, e = "I", "will", "be", "merged"
# c, d, e 会被合并为一个数组 a
> say_hello(c, d, e)
> I
will
be
merged
Array
Ampersand \&
调用方法时, \& 把一个 proc 对象转化为块,并传递给方法。
my_proc = proc { "Jerusalem" }
def say_hello(greeting)
"#{greeting} #{yield}"
end
# 以下两种写法相似
say_hello("hello", &my_proc)
say_hello("hello"){"Jerusalem"}
在定义方法时,\& 方法内部会把传递进来的块转化为 proc。
def say_hello(greeting, &jerusalem)
# It's a proc
p jerusalem.class
end
Recommend
-
70
README.md vim-asterisk: * -Improved
-
75
Take a look at thethree previous articles, and you will see that understanding the glue that joins them together is as important...
-
48
README.md The Asterisk(R) Open Source PBX By Mark Spencer <[email protected]> and the Asterisk.org developer communit...
-
28
A few months ago, Google Photos product lead, David Lieb, told us that manually tagging faces was
-
28
If you are a Javascript developer I am pretty sure you have written things like this in the past: object.prop.doSomething();and JS comes along and slaps you in the face: Uncaught TypeError: Cannot read property 'doSomething' of undefinedThe reas...
-
29
Turn asterisk-indented text lines into mind maps. Contribute to lucasepe/crumbs development by creating an account on GitHub.
-
10
Ampersand in NativeMessaging Host's path prevents launching it
-
18
Operator linq as * (asterisk) in sql advertisements I want to select all the fields of one table, and only specifics fields of a second table....
-
4
Ampersand & OAuth2, Part 1: Local Storage July 2, 2015 · ~1500 words (7 min) We’re going to try something new today. We’re going to remember I’m a developer, and I’m going to post some code o...
-
9
Google is rebranding Arts & Culture with new ampersand logo August 26, 2022 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK