mat*_*ths 3 ruby syntax programming-languages
Ruby对块有一种有趣的语法(管道之间的参数,后跟一系列语句):
[1, 2, 3].each do |x|
puts x
end
Run Code Online (Sandbox Code Playgroud)
Rust也使用类似的语法:
arr.sort_by_key(|a| {
let intermediate_value = some_function(a);
intermediate_value + 10
});
Run Code Online (Sandbox Code Playgroud)
我想知道这种语法是否早于Ruby(特别是在管道之间放置参数,我相信我在其他地方也看到过,但不确定在哪里),如果是的话,什么语言使用它?
我相信Smalltalk也使用管道,但用于对象初始化,在Google上找不到其他示例。
谢谢!
Ruby的创建者“ Matz”曾表示,Ruby的设计灵感来自Perl,Smalltalk,Eiffel,Ada和Lisp。
从这个列表中,我想说的是最有可能来自Smalltalk,Eiffel和Lisp。例子:
短暂聊天
#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]
Run Code Online (Sandbox Code Playgroud)
#(1 2 3 4 5) fold: [:product :number | product * number]
Run Code Online (Sandbox Code Playgroud)
Lisp
#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]
Run Code Online (Sandbox Code Playgroud)
#(1 2 3 4 5) fold: [:product :number | product * number]
Run Code Online (Sandbox Code Playgroud)
艾菲尔
class
APPLICATION
create
make
feature {NONE}
make
local
test: ARRAY [INTEGER]
do
create test.make_empty
test := <<5, 1, 9, 7>>
io.put_string ("Sum: " + sum (test).out)
io.new_line
io.put_string ("Product: " + product (test).out)
end
sum (ar: ARRAY [INTEGER]): INTEGER
-- Sum of the items of the array 'ar'.
do
across
ar.lower |..| ar.upper as c
loop
Result := Result + ar [c.item]
end
end
product (ar: ARRAY [INTEGER]): INTEGER
-- Product of the items of the array 'ar'.
do
Result := 1
across
ar.lower |..| ar.upper as c
loop
Result := Result * ar [c.item]
end
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |