结合多个Ruby函数

时间:2013-12-16 22:20:56

标签: ruby regex

将这些结合起来是一种简单的方法吗? 我正在尝试删除整数,浮点数和特定单词

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 个答案:

答案 0 :(得分:2)

使用正则表达式:

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

要移除连续空格的行(即basic cards - > basic cards),请尝试:

string = string.squeeze(' ').strip

答案 1 :(得分: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 "

添加字边界检查可防止字符串匹配和误报。