有人可以解释Ruby在块中使用竖线字符吗? [英] Can someone explain Ruby's use of pipe characters in a block?

查看:247
本文介绍了有人可以解释Ruby在块中使用竖线字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释Ruby在块中使用竖线字符吗?我了解它包含一个变量名,该变量名将在迭代时分配给数据.但是,这叫什么呢?管道内可以有多个变量吗?我还有什么要知道的吗?有任何良好链接可以获得更多信息吗?

Can someone explain to me Ruby's use of pipe characters in a block? I understand that it contains a variable name that will be assigned the data as it iterates. But what is this called? Can there be more than one variable inside the pipes? Anything else I should know about it? Any good links to more information on it?

例如:

25.times { | i | puts i }

推荐答案

大括号定义了一个匿名函数,称为块.管道之间的标记是此块的参数.所需参数的数量取决于该块的使用方式.每次评估该块时,要求该块的方法将基于调用它的对象传递一个值.

Braces define an anonymous function, called a block. Tokens between the pipe are the arguments of this block. The number of arguments required depends on how the block is used. Each time the block is evaluated, the method requiring the block will pass a value based on the object calling it.

与定义方法相同,只是不将其存储在接受块的方法之外.

It's the same as defining a method, only it's not stored beyond the method that accepts a block.

例如:

def my_print(i) 
  puts i
end

在执行时将执行以下操作:

will do the same as this when executed:

{|i| puts i}

唯一的区别是该块是动态定义的,没有存储.

the only difference is the block is defined on the fly and not stored.

示例2: 以下语句是等效的

Example 2: The following statements are equivalent

25.times &method(:my_print)

25.times {|i| puts i}

我们使用匿名块,因为作为块传递的大多数功能通常是特定于您的情况的,因此不值得定义以供重用.

We use anonymous blocks because the majority of functions passed as a block are usually specific to your situation and not worth defining for reuse.

那么当方法接受一个块时会发生什么呢?这取决于方法.接受一个块的方法将通过一种定义良好的方式从其调用对象传递值来对其进行调用.返回的内容取决于需要该块的方法.

So what happens when a method accepts a block? That depends on the method. Methods that accept a block will call it by passing values from their calling object in a well defined manner. What's returned depends on the method requiring the block.

例如:在25.times {|i| puts i}中,times为0与其调用者的值之间的每个值调用一次该块,并将该值作为临时变量i传递到该块中. Times返回调用对象的值.在这种情况下为25.

For example: In 25.times {|i| puts i} .times calls the block once for each value between 0 and the value of its caller, passing the value into the block as the temporary variable i. Times returns the value of the calling object. In this case 25.

让我们看一下接受带有两个参数的块的方法.

Let's look at method that accepts a block with two arguments.

{:key1 => "value1", :key2 => "value2"}.each {|key,value| 
     puts "This key is: #{key}. Its value is #{value}"
}

在这种情况下,每个密钥/值对都将块键作为第一个参数,并将值作为第二个参数.

In this case each calls the block ones for each key/value pair passing the key as the first argument and the value as the second argument.

这篇关于有人可以解释Ruby在块中使用竖线字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆