ruby - Ruby 的 block 语法的起源是什么?

标签 ruby syntax programming-languages

Ruby 有一个有趣的 block 语法(管道之间的参数后跟一系列语句):

[1, 2, 3].each do |x|
    puts x
end

Rust 也使用类似的语法:

arr.sort_by_key(|a| {
    let intermediate_value = some_function(a);
    intermediate_value + 10
});

我想知道这种语法是否早于 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]
#(1 2 3 4 5) fold: [:product :number | product * number]

口齿不清

(let ((data #(1 2 3 4 5)))     ; the array
  (values (reduce #'+ data)       ; sum
          (reduce #'* data)))     ; product
(loop for i in '(1 2 3 4 5) sum i)

埃菲尔铁塔

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

关于ruby - Ruby 的 block 语法的起源是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737735/

相关文章:

ruby-on-rails - rails : get session timeout

ruby-on-rails - 无法加载 ruby​​ textmate?

ruby-on-rails - 在 respond_to block 中共享代码

ruby-on-rails - 用 mocha stub 时替换方法实现

syntax - 这种符号的名称是什么?

php - 用于 PHP 的文本到 HTML 转换器

java - 为什么 equals() 中的顺序相反

java - 当我读/写文件时发生了什么(在操作系统级别)?

apache-flex - 为什么Flex的ArrayCollection的Contain方法查看内存引用?

c++ - 在 C++ 中的循环中创建新变量时有什么更好的