2016-06-25 56 views
-3

我是一個新手紅寶石。當我嘗試閱讀沒有換行符的行時,我學習了chomp方法。此方法用於從字符串的末尾刪除\ n。所以,我嘗試了以下場景。使用!和紅寶石chomp方法

計劃:

arr = Array.new; 

while true 
    char = gets  // Read line from input 
    if char == nil  // If EOF reach then break 
     break 
    end 
    char.chomp  // Try to remove \n at the end of string 
    arr << char  // Append the line into array 
end 

p arr   // print the array 

輸出:

$ ruby Array.rb 
abc 
def 
["abc\n", "def\n"] 
$ 

但它不會在字符串的結尾去掉換行符。但是如果'!'在chomp(char.chomp!)的末尾提供,它工作正常。所以 '!'的需求是什麼以及爲什麼使用它?什麼 !代表 ?

+2

使用'#'s在Ruby中進行註釋。 –

回答

5

作爲good documentation says,chomp返回一個新字符串,刪除了換行符,而chomp!修改字符串本身。

因此,char.chomp // Try to remove \n at the end of string會返回一個新的字符串,但您並未將新行字符串分配給任何變量。

以下是可能的解決方法:

char.chomp!  // Try to remove \n at the end of string 
arr << char  // Append the line into array 

str = char.chomp  // Try to remove \n at the end of string 
arr << str  // Append the line into array 

arr << char.chomp  // Append the line into array 
+0

所以,如果我使用!在該方法結束時,操作接受對象本身。這樣對嗎? – mrg

+0

在這個特定的情況下,是的。 – Zabba

+1

@mrg:不是。它與'!'完全沒有任何關係。 Ruby不關心這些方法的調用方式。他們可以被稱爲'strip_whitespace'和'strip_whitespace_destructive'。它們恰好被稱爲'chomp'和'chomp!',但它們也可以稱爲'foo'和'bar'。 –

0

當你這樣做char.chomp則輸出不會有\n字符,但裏面char字符串將保持不變,在紅寶石!是一種用於改變對象本身的方法之後的約定,這並不意味着只需在方法中添加!就可以改變該對象,但這只是方法定義中遵循的一種約定,所以如果你做char.chomp!它會改變字符本身的值,這就是爲什麼你看到正確的結果。你可以在這裏做的僅僅是arr << char.chomp,這會將沒有\n的值加到你的數組中,也不會改變實際的對象。

+0

'紅寶石!用於改變對象本身的方法後=>這實際上是不正確的。 '!'只是一個你可以在方法名中使用的字符。雖然常見的慣例是使用'!'表示對象的破壞性或原地修改,但情況並非總是如此。使用'!'並不意味着它總是修改對象。 – Zabba

+0

是的,這是真的,我的意思是這是一個在大多數方法中遵循的慣例,我編輯了我的迴應。 – Saad

-1

結束於的方法!表示該方法將修改它所調用的對象。 Ruby稱這些「危險的方法」,因爲它們改變了別人可能引用的狀態。

arr = Array.new; 

    while true 
     char = gets  
     if char == nil  
      break 
     end 

     char.chomp  
     puts char 

    // result = 'your string/n' (The object reference hasn't got changed.) 

    char2 = char.chomp 

    puts char2 

    // result = 'your string' (The variable changed but not the object reference) 

    char.chomp! 

    puts char 

    // result = 'your string' (The object reference chaned) 

    Now you can either do, 

    arr << char  // Append the line into array 

    or, 

    arr << char2  
    end 

    p arr   // print the array 

他們都給你同樣的結果。

+0

最新的投票理由是什麼,你在其中發現了什麼錯誤? – Sravan