关于Ruby <<运算符的澄清

yre*_*uta 7 ruby oop

我是Ruby的新手,我想知道<<运营商.当我用Google搜索这个运算符时,它说这是一个二进制左移运算符给出了这个例子:

a << 2会给出15哪个1111 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
Run Code Online (Sandbox Code Playgroud)

这个问题似乎并不在我所提供的代码申请.所以使用我的代码,Ruby <<运算符如何工作?

Jör*_*tag 32

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

a << b
Run Code Online (Sandbox Code Playgroud)

意味着a它应该意味着什么决定.<<不知道什么a是不可能说出什么意思.

作为一般惯例,<<在Ruby中意味着"追加",即它将其参数附加到其接收器然后返回接收器.因此,因为Array它将参数附加到数组,因为String它执行字符串连接,因为Set它将参数添加到集合,因为IO它写入文件描述符,依此类推.

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


Joh*_*hir 11

<<只是一种方法.它在某种意义上通常意味着"附加",但可以表示任何意义.对于字符串和数组,它意味着追加/添加.对于整数,它是按位移位.

试试这个:

class Foo
  def << (message)
    print "hello " + message
  end
end

f = Foo.new
f << "john" # => hello john
Run Code Online (Sandbox Code Playgroud)


rob*_*rit 7

在 Ruby 中,操作符只是方法。根据变量的类别,<<可以做不同的事情:

# 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]
Run Code Online (Sandbox Code Playgroud)

这一切都取决于类定义的内容<<