关于Ruby的澄清<<操作员 [英] Clarification on the Ruby << Operator
问题描述
我对Ruby还是很陌生,想知道<<
运算符.当我用谷歌搜索这个运算符时,给出的例子表明它是一个二进制左移运算符:
I am quite new to Ruby and am wondering about the <<
operator. When I googled this operator, it says that it is a Binary Left Shift Operator given this example:
a << 2
将给出15
,即1111 0000
但是,在此代码中,它似乎不是二进制左移运算符":
however, it does not seem to be a "Binary Left Shift Operator" in this code:
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
和此问题似乎不适用于我给出的代码.那么使用我拥有的代码,Ruby <<
运算符如何工作?
and this question does not seem to apply in the code I have given. So with the code I have, how does the Ruby <<
operator work?
推荐答案
Ruby是一种面向对象的语言.面向对象的基本原理是对象将消息发送到其他对象,并且消息的接收者可以以其认为合适的任何方式响应消息.因此,
Ruby is an object-oriented language. The fundamental principle of object orientation is that objects send messages to other objects, and the receiver of the message can respond to the message in whatever way it sees fit. So,
a << b
表示a
所决定的含义.不知道a
是什么,就不可能说出<<
是什么意思.
means whatever a
decides it should mean. It's impossible to say what <<
means without knowing what a
is.
作为一般约定,Ruby中的<<
表示附加",即,将其参数附加到其接收方,然后返回接收方.因此,对于Array
,它将参数附加到数组中;对于String
,它将执行字符串连接;对于Set
,它将参数添加到集合中;对于IO
,它将写入文件描述符中,依此类推.
As a general convention, <<
in Ruby means "append", i.e. it appends its argument to its receiver and then returns the receiver. So, for Array
it appends the argument to the array, for String
it performs string concatenation, for Set
it adds the argument to the set, for IO
it writes to the file descriptor, and so on.
作为特殊情况,对于Fixnum
和Bignum
,它对Integer
的二进制补码表示形式进行按位左移.这主要是因为这就是在C语言中所做的事情,而Ruby受C语言的影响.
As a special case, for Fixnum
and Bignum
, it performs a bitwise left-shift of the twos-complement representation of the Integer
. This is mainly because that's what it does in C, and Ruby is influenced by C.
这篇关于关于Ruby的澄清<<操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!