我只想删除字符串中的一部分。
我的字符串:MatchParent
需要输出:"&product=Software"
尝试"Software"
,delete
,split
但不起作用。有人可以帮我吗?我对Ruby非常陌生。
答案 0 :(得分:1)
这有点令人惊讶,但Ruby允许你使用[]
并分配给#34;覆盖"要替换的子字符串:
x = "&product=Software"
x['&product='] = ''
x # "Software"
答案 1 :(得分:0)
str = "&product=Software"
str['&product='] = '' # method 1
str.sub!('&product=', '') # method 2
但如果你想更聪明的话......
str = '&product=Software&price=19.99'
h = {}
str.split('&').each do |s|
next if s.length == 0
key, val = s.split '='
h[key] = val
end
puts h # {"product"=>"Software", "price"=>"19.99"}
答案 2 :(得分:0)
实现这一目标的另外两种方法:
使用分割:
2.3.0 :014 > "&product=software".split('=')[1]
=> "software"
使用sub:
2.3.0 :015 > "&product=software".sub(/^.*?=/,'')
=> "software"