Ruby删除方法(字符串操作)
我是 Ruby 新手,一直在学习 Mr Neighborly 的 Humble Little Ruby Guide。在此过程中,代码示例中出现了一些拼写错误,但我总是设法找出问题所在并随后修复它 - 直到现在!
这确实很基本,但我无法让以下示例在 Mac OS X(雪豹)上工作:
gone = "Got gone fool!"
puts "Original: " + gone
gone.delete!("o", "r-v")
puts "deleted: " + gone
我期望的输出是:
Original: Got gone fool!
deleted: G gne fl!
我实际得到的输出是:
Original: Got gone fool!
deleted: Got gone fool!
删除!方法似乎没有任何效果。
任何人都可以阐明这里出了什么问题吗? :-\
I'm new to Ruby, and have been working my way through Mr Neighborly's Humble Little Ruby Guide. There have been a few typos in the code examples along the way, but I've always managed to work out what's wrong and subsequently fix it - until now!
This is really basic, but I can't get the following example to work on Mac OS X (Snow Leopard):
gone = "Got gone fool!"
puts "Original: " + gone
gone.delete!("o", "r-v")
puts "deleted: " + gone
Output I'm expecting is:
Original: Got gone fool!
deleted: G gne fl!
Output I actually get is:
Original: Got gone fool!
deleted: Got gone fool!
The delete! method doesn't seem to have had any effect.
Can anyone shed any light on what's going wrong here? :-\
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
String.delete
方法(记录在此处 ) 将其参数视为数组,然后根据其数组的交集删除字符。两个数组的交集是两个数组共有的所有字符。因此,您最初删除的
gone.delete!("o", "rv")
将变为There are no character present in two arrays,因此删除将得到一个空数组,因此不会删除任何字符。
The
String.delete
method (Documented here) treats its arguments as arrays and then deletes characters based upon the intersection of its arrays.The intersection of 2 arrays is all characters that are common to both arrays. So your original delete of
gone.delete!("o", "r-v")
would becomeThere are no characters present in both arrays so the deletion would get an empty array, hence no characters are deleted.
我更改
为
并且效果很好。
I changed
to
and it works fine.
您使用不同的方式获得相同的o/p,例如 gsub
o/ p
You get same o/p using some different way like gsub
o/p