2013-12-16 100 views
1

將這些功能結合起來最簡單的方法是什麼? 我試圖刪除整數,浮點數,和特定的詞結合多個Ruby功能

string = "5 basic sent cards by 4.55" 

string.delete("0-9.") 
string.slice! "sent" 
string.slice! "by" 

puts string 

#desired output: basic cards 

回答

2

使用正則表達式:

string.gsub! /[0-9.]|sent|by/, '' 

要刪除連續空間的運行(即basic cards - >basic cards),嘗試:

string = string.squeeze(' ').strip 
+0

謝謝!學習ruby有什麼好方法?除了困難的方式。 – neil4real

+0

@ neil4real讀一本書;)沒有「簡單的方法」。 – Doorknob

+0

我得到這個輸出之前和之後的空間,任何方式刪除它們? – neil4real

1

小心使用正則表達式:天真的模式可以是非常具有破壞性的輸入:

"5 basic sent cards by 4.55".gsub(/[0-9.]|sent|by/, '') # => " basic cards " 
"5 basic present cards bye 4.55".gsub(/[0-9.]|sent|by/, '') # => " basic pre cards e " 

"5 basic sent cards by 4.55".gsub(/[\d.]+|\b(?:sent|by)\b/, '') # => " basic cards " 
"5 basic present cards bye 4.55".gsub(/[\d.]+|\b(?:sent|by)\b/, '') # => " basic present cards bye " 

添加字邊界檢查可防止字符串內匹配和誤報。