【问题标题】:Clarification on the Ruby << Operator关于 Ruby << 运算符的说明
【发布时间】:2012-04-01 14:02:33
【问题描述】:

我对 Ruby 很陌生,我想知道 &lt;&lt; 运算符。当我用谷歌搜索这个运算符时,它说它是一个二进制左移运算符,给出了这个例子:

a &lt;&lt; 2 将给出151111 0000

但是,在这段代码中,它似乎不是“二进制左移运算符”:

class TextCompressor
  attr_reader :unique, :index

  def initialize(text)
    @unique = []
    @index = []

    add_text(text)
  end

  def add_text(text)
    words = text.split
    words.each { |word| do add_word(word) }
  end

  def add_word(word)
    i = unique_index_of(word) || add_unique_word(word)
    @index << i
  end

  def unique_index_of(word)
    @unique.index(word)
  end

  def add_unique_word
    @unique << word
    unique.size - 1
  end
end

this question 似乎不适用于我给出的代码。那么使用我的代码,Ruby &lt;&lt; 运算符是如何工作的?

【问题讨论】:

  • 它根据“a”是什么做不同的事情。 1 &lt;&lt; 4 # =&gt; 16,这是预期的。 (在这种情况下,“a”是Fixnum。请记住,运算符只是方法,因此可以写成:上面的1.__send__(:&lt;&lt;, 16);这也意味着运算符,至少&lt;&lt;,是多态 在他们的第一个参数上。)
  • 你不能用谷歌搜索它,但你可以用符号搜索它:symbolhound.com/?q=array+%3C%3C
  • @AndrewGrimm 你让我把咖啡洒了。我一直在寻找这样的工具 很长时间了。
  • @AndrewGrimm 天哪,这可以合法地让生活变得如此轻松!

标签: ruby oop


【解决方案1】:

在 Ruby 中,运算符只是方法。根据变量的类别,&lt;&lt; 可以做不同的事情:

# For integers it means bitwise left shift:
5 << 1  # gives 10
17 << 3 # gives 136

# arrays and strings, it means append:
"hello, " << "world"   # gives "hello, world"
[1, 2, 3] << 4         # gives [1, 2, 3, 4]

这完全取决于类将&lt;&lt; 定义为什么。

【讨论】:

    【解决方案2】:

    Ruby 是一种面向对象的语言。面向对象的基本原则是对象向其他对象发送消息,消息的接收者可以以任何它认为合适的方式响应消息。所以,

    a << b
    

    表示a 决定的任何含义。如果不知道a 是什么,就不可能说出&lt;&lt; 的含义。

    作为一般约定,&lt;&lt; 在 Ruby 中的意思是“附加”,即它将其参数附加到其接收者,然后返回接收者。因此,对于Array,它将参数附加到数组,对于String,它执行字符串连接,对于Set,它将参数添加到集合中,对于IO,它写入文件描述符,等等。

    作为一种特殊情况,对于FixnumBignum,它执行Integer 的二进制补码表示的按位左移。这主要是因为它在 C 中就是这样做的,而 Ruby 受 C 的影响。

    【讨论】:

      【解决方案3】:

      &lt;&lt; 是一个运算符,它是用于在给定对象上调用 &lt;&lt; 方法的语法糖。在Fixnum it is defined to bitshift left 上,但它具有不同的含义,具体取决于它所定义的类。例如,对于Array it adds (or, rather, "shovels") the object into the array

      我们可以在这里看到&lt;&lt; 确实只是方法调用的语法糖:

      [] << 1   # => [1]
      [].<<(1)  # => [1]
      

      因此在您的情况下,它只是在@unique 上调用&lt;&lt;,在这种情况下是Array

      【讨论】:

        【解决方案4】:

        试试这个:

        class Foo
          def << (message)
            print "hello " + message
          end
        end
        
        f = Foo.new
        f << "john" # => hello john
        

        【讨论】:

          【解决方案5】:
          猜你喜欢
          • 2019-05-14
          • 2013-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多