<< 是什么意思?在 Ruby 中是什么意思?

发布于 2024-11-26 19:55:56 字数 317 浏览 0 评论 0 原文

我有代码:

  def make_all_thumbs(source)
    sizes = ['1000','1100','1200','800','600']
    threads = []
    sizes.each do |s|
      threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }
    end
  end

<< 是什么意思?

I have code:

  def make_all_thumbs(source)
    sizes = ['1000','1100','1200','800','600']
    threads = []
    sizes.each do |s|
      threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }
    end
  end

what does << mean?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

并安 2024-12-03 19:55:56

它可以有 3 个不同的含义:

'<<'作为普通方法

在大多数情况下 '<<'是一个像其他方法一样定义的方法,在您的情况下,它意味着“添加到该数组的末尾”(另请参见 此处)。

这是针对您的特定情况,但在很多其他情况下您也会遇到“<<”方法。我不会将其称为“运算符”,因为它实际上是在某个对象上定义的方法,可以由您覆盖或为您自己的对象实现。 '<<' 的其他情况

  • 字符串连接:“a”<< "b"
  • 将输出写入 IO:io << "一行文本\n"
  • 将数据写入消息摘要、HMAC 或密码: sha << OpenSSL::BN 的“要散列的文本”
  • 左移: bn << 2
  • ...

单例类定义

然后,程序流程中存在当前作用域的神秘转变(=自身的更改):

class A
  class << self
    puts self # self is the singleton class of A
  end
end

a = A.new
class << a
  puts self # now it's the singleton class of object a
end

神秘的 class << self 让我想知道并调查那里的内部结构。而在我提到的所有示例中 << 实际上是在类中定义的方法,即

obj << stuff

相当于

obj.<<(stuff)

class << self(或任何代替 self 的对象)构造确实不同。它实际上是语言本身的内置功能,在 CRuby 中,它在 parse.y 中定义为

k_class tLSHFT expr

k_class 是“class”关键字,其中 tLSHFT 是一个 '<<' token 和expr 是任意表达式。也就是说,您实际上可以编写

class << <any expression>

并将转移到表达式结果的单例类中。 tLSHFT 序列将被解析为“NODE_SCLASS”表达式,称为单例类定义(参见node.c)

case NODE_SCLASS:
    ANN("singleton class definition");
    ANN("format: class << [nd_recv]; [nd_body]; end");
    ANN("example: class << obj; ..; end");
    F_NODE(nd_recv, "receiver");
    LAST_NODE;
    F_NODE(nd_body, "singleton class definition");
    break; 

此处文档

此处文档使用“<<”以一种完全不同的方式。您可以通过声明来方便地定义跨多行的字符串

here_doc = <<_EOS_
The quick brown fox jumps over the lazy dog.
...
_EOS_

。为了区分“here doc 运算符”,任意字符串分隔符必须紧跟在“<<”之后。初始分隔符和第二次出现的同一分隔符之间的所有内容都将成为最终字符串的一部分。也可以使用“<<-”,区别在于使用后者将忽略任何前导或尾随空格。

It can have 3 distinct meanings:

'<<' as an ordinary method

In most cases '<<' is a method defined like the rest of them, in your case it means "add to the end of this array" (see also here).

That's in your particular case, but there are also a lot of other occasions where you'll encounter the "<<" method. I won't call it 'operator' since it's really a method that is defined on some object that can be overridden by you or implemented for your own objects. Other cases of '<<'

  • String concatenation: "a" << "b"
  • Writing output to an IO: io << "A line of text\n"
  • Writing data to a message digest, HMAC or cipher: sha << "Text to be hashed"
  • left-shifting of an OpenSSL::BN: bn << 2
  • ...

Singleton class definition

Then there is the mysterious shift of the current scope (=change of self) within the program flow:

class A
  class << self
    puts self # self is the singleton class of A
  end
end

a = A.new
class << a
  puts self # now it's the singleton class of object a
end

The mystery class << self made me wonder and investigate about the internals there. Whereas in all the examples I mentioned << is really a method defined in a class, i.e.

obj << stuff

is equivalent to

obj.<<(stuff)

the class << self (or any object in place of self) construct is truly different. It is really a builtin feature of the language itself, in CRuby it's defined in parse.y as

k_class tLSHFT expr

k_class is the 'class' keyword, where tLSHFT is a '<<' token and expr is an arbitrary expression. That is, you can actually write

class << <any expression>

and will get shifted into the singleton class of the result of the expression. The tLSHFT sequence will be parsed as a 'NODE_SCLASS' expression, which is called a Singleton Class definition (cf. node.c)

case NODE_SCLASS:
    ANN("singleton class definition");
    ANN("format: class << [nd_recv]; [nd_body]; end");
    ANN("example: class << obj; ..; end");
    F_NODE(nd_recv, "receiver");
    LAST_NODE;
    F_NODE(nd_body, "singleton class definition");
    break; 

Here Documents

Here Documents use '<<' in a way that is again totally different. You can define a string that spans over multiple lines conveniently by declaring

here_doc = <<_EOS_
The quick brown fox jumps over the lazy dog.
...
_EOS_

To distinguish the 'here doc operator' an arbitrary String delimiter has to immediately follow the '<<'. Everything inbetween that initial delimiter and the second occurrence of that same delimiter will be part of the final string. It is also possible to use '<<-', the difference is that using the latter will ignore any leading or trailing whitespace.

乙白 2024-12-03 19:55:56

主要用于数组中,将值附加到数组末尾。

a = ["orange"]
a << "apple"
puts a

给出这个

  ["orange", "apple"] 

result.

Mostly used in arrays to append the value to the end of the array.

a = ["orange"]
a << "apple"
puts a

gives this

  ["orange", "apple"] 

result.

待"谢繁草 2024-12-03 19:55:56

'一<< b' 表示将 b 添加到 a 的末尾

'a << b' means append b to the end of a

吹泡泡o 2024-12-03 19:55:56

该运算符允许您通过附加新项目来提供现有数组。

在上面的示例中,您只是用 5 个新线程填充空数组 threads

It's the operator which allows you to feed existing arrays, by appending new items.

In the example above you are just populating the empty array threads with 5 new threads.

白衬杉格子梦 2024-12-03 19:55:56

在 Ruby 中,你总是有更多单一的方法来做事。因此,Ruby 对常用方法名称有一些不错的快捷方式。就像这个用于 .push 而不是键入 .push 方法名称,您可以简单地使用 <<(串联运算符)。事实上,在某些情况下,您可以将其中任何一个用于相同的操作 .push 和 + 以及 <<。

就像您在这个示例中看到的那样:

alphabet = ["a", "b", "c"]
alphabet << "d" # Update me!
alphabet.push("e") # Update me!
print alphabet 
caption = "the boy is surrounded by "
caption << "weezards!" # Me, too!
caption += " and more. " # Me, too!
# .push can no be uses for concatenate 
print caption

所以您看到的结果是:

["a", "b", "c", "d", "e"]
the boy is surrounded by weezards! and more.

您可以使用运算符 <<将一个元素推入数组或将一个字符串连接到另一个。

所以,它所做的就是创建一个新的元素/对象 Thread 类型并将其推入数组中。

 threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }

In ruby you always have more the one way to do things. So, Ruby has some nice shortcuts for common method names. like this one is for .push instead of typing out the .push method name, you can simply use <<, the concatenation operator. in fact in some cases you can use any of these for the same operation .push and + with <<.

Like you can see in this example:

alphabet = ["a", "b", "c"]
alphabet << "d" # Update me!
alphabet.push("e") # Update me!
print alphabet 
caption = "the boy is surrounded by "
caption << "weezards!" # Me, too!
caption += " and more. " # Me, too!
# .push can no be uses for concatenate 
print caption

so you see the result is:

["a", "b", "c", "d", "e"]
the boy is surrounded by weezards! and more.

you can use the operator << to push a element into an array or to concatenate a string to another.

so, what this is this doing is creating a new element/object Thread type and pushing it into the array.

 threads << Thread.new(s) {
        create_thumbnail(source+'.png', source+'-'+s+'.png', s)
      }
淡忘如思 2024-12-03 19:55:56

在红宝石中 '<<'运算符主要用于:

  1. 在数组中附加一个值(在最后一个位置)

    [2,4,6]<< 8
    它将给出 [2, 4, 6, 8]

  2. 它也用于 ruby​​ 中的一些活动记录操作。例如,我们有一个 Cart 和 LineItem 模型,关联为 cart has_many line_items。 Cart.find(A).line_items 将返回 ActiveRecord::Associations 对象,其中包含属于购物车“A”的订单项。

现在,要将另一个 line_item (X) 添加(或关联)到购物车 (A),

Cart.find(A).line_items << LineItem.find(X)
  1. 现在将另一个 LineItem 添加到同一购物车“A”,但这次我们不会创建任何 line_item 对象(我的意思是不会手动创建 activerecord 对象)

    Cart.find(A).line_items << LineItem.new

在上面的代码中<<将保存对象并将其附加到左侧活动记录关联数组。

上面的答案已经涵盖了许多其他内容。

In ruby '<<' operator is basically used for:

  1. Appending a value in the array (at last position)

    [2, 4, 6] << 8
    It will give [2, 4, 6, 8]

  2. It also used for some active record operations in ruby. For example we have a Cart and LineItem model associated as cart has_many line_items. Cart.find(A).line_items will return ActiveRecord::Associations object with line items that belongs to cart 'A'.

Now, to add (or say to associate) another line_item (X) to cart (A),

Cart.find(A).line_items << LineItem.find(X)
  1. Now to add another LineItem to the same cart 'A', but this time we will not going to create any line_item object (I mean will not create activerecord object manually)

    Cart.find(A).line_items << LineItem.new

In above code << will save object and append it to left side active record association array.

And many others which are already covered in above answers.

ζ澈沫 2024-12-03 19:55:56

另外,从 Ruby 2.6 开始,<< 方法也在 Proc 上定义。

Proc#<< 允许组成两个或多个过程。

Also, since Ruby 2.6, the << method is defined also on Proc.

Proc#<< allows to compose two or more procs.

不羁少年 2024-12-03 19:55:56

意思是添加到末尾(追加)。

a = [1,2,3]
a << 4
a = [1,2,3,4]

It means add to the end (append).

a = [1,2,3]
a << 4
a = [1,2,3,4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文