2012-03-16 93 views
3

我對Ruby非常陌生,並且對<<運算符感到疑惑。當我用Google搜索這個操作符,它說,它是給這個例子二進制向左移位運算符:關於Ruby的澄清<<操作符

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 

this question似乎並不在我所提供的代碼申請。因此,使用我的代碼,Ruby <<運算符是如何工作的?

+2

它根據什麼「a」做了不同的事情。這是預期的。 (在這種情況下,「a」是一個「Fixnum」,記住操作符只是方法,所以它可以寫成:'1 .__ send __(:<<,16)';這也意味着操作符,最少的<< <<,在他們的第一個參數上是* polymorphic *) – 2012-03-16 00:44:03

+4

你不能谷歌它,但你可以symbolhound它:http://symbolhound.com/?q=array+%3C%3C – 2012-03-16 01:26:52

+1

@AndrewGrimm你讓我泄漏了我的一杯咖啡。我一直在尋找像這樣的工具。 – user2398029 2012-03-16 02:27:26

回答

18

Ruby是一種面向對象的語言。面向對象的基本原則是對象將消息發送給其他對象,並且消息的接收者可以以任何合適的方式對消息作出響應。所以,

a << b 

意味着什麼a決定它的意思。不可能說什麼<<意味着不知道a是什麼。

作爲一般慣例,在<<紅寶石的意思是「追加」,即它追加它的參數到它的接收器,然後返回接收器。因此,對於Array其附加的參數數組,爲String它執行字符串連接,爲Set其添加的參數設定,爲IO其寫入文件描述符,等等。

作爲特殊情況,對於FixnumBignum,它執行Integer的二進制補碼錶示的按位左移。這主要是因爲這就是它在C中的作用,Ruby受C影響。

6

< <只是一種方法。它在某種意義上通常意味着「追加」,但意味着什麼。對於字符串和數組,它意味着追加/添加。對於整數它是按位移。

試試這個:

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

f = Foo.new 
f << "john" # => hello john 
2

在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] 

這一切都取決於什麼類定義<<是。