2013-11-24 46 views
2

我是Ruby的新手。我正在嘗試製作一些簡單的計算器程序。所以,基本上它應該做的就是輸入如 4 + 2 之類的東西,並輸出6.簡單,對吧?所以我認爲。我試圖在所有操作字符中分割一個字符串,所以我讓這個快速的正則表達式認爲它會起作用。它沒有。試圖分割一個字符串(紅寶石)

class Calculator 
def add(a,b) 
    return a+b 
end 
def sub(a,b) 
    return a-b 
end 
def div(a,b) 
    return a/b 
end 
def mul(a,b) 
    return a*b 
end 
end 

operation = gets.split("[\/\+\-\*]") 
print(operation) 
sleep() 

sleep()有暫停控制檯,所以我可以看看我的輸出。但現在,它輸出["4+2\n"] ??我不知道我做錯了什麼。我需要一些幫助。 (它應該輸出["4","+","2"])。提前致謝。

回答

1

對於要使用/,而不是"正則表達式:

operation = gets.split(/[\/\+\-\*]/) # ["4", "2\n"]

有額外的換行符刪除與條:

operation = gets.strip.split(/[\/\+\-\*]/) # ["4", "2"]

但我們失去了運營商。縱觀文檔爲split

如果模式包含組,各自的比賽將在數組中返回 爲好。

在我們的正則表達式中添加()創建一個組。然後我們有:

operation = gets.strip.split(/([\/\+\-\*])/) # ["4", "+", "2"]

+0

感謝這麼多,但我不明白的gets.strip.split。我知道它會去掉換行符,但不應該是'gets.split(不管).strip'嗎? – hexagonest

+2

Split返回一個數組。 strip對字符串進行操作,我在調用split之前刪除了newling。 –

+0

-1在發佈正則表達式答案之前學習在regex中逃脫什麼。 – pguardiario

2

你並不需要每一個角色逃過你的字符類的內部。考慮以下幾點:

operation = gets.gsub(/[^\d\/*+-]/, '').split(/([\/*+-])/) 

operation = gets.split(/([\/*+-])/).map(&:strip) 
+0

是的,但使用'\ d'而不是'0-9' – pguardiario

+0

好點。 – hwnd

0

你可以試試下面的代碼。

operation = gets.chomp.gsub(/[\/\+\-\*]/, ';\0;').split(";") 
print(operation) 

執行結果:

4+2/3*9-0 
["4", "+", "2", "/", "3", "*", "9", "-", "0"]