2016-10-01 29 views
-1

我只想从字符串中删除一部分。从ruby中的字符串中删除一部分

我的字符串:"&product=Software"

需要输出:"Software"

试过deletesplitslice但不起作用。有人可以帮助我吗?我对Ruby非常陌生。

+0

' “&产品=软件” .split( “=”)last' – Abhi

+0

我不想阵列和其他部分。我只想将软件作为输出字符串。 –

+1

@ User0234'.split.last'就是这样做的。 – meagar

回答

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"} 
1

这是稍微奇怪,但Ruby允许你使用[]和分配“覆盖”你想要的子取代:

x = "&product=Software" 

x['&product='] = '' 

x # "Software" 
0

实现这一目标的另两种方式:

采用分体式:

2.3.0 :014 > "&product=software".split('=')[1] 
=> "software" 

使用子:

2.3.0 :015 > "&product=software".sub(/^.*?=/,'') 
=> "software"