Ruby删除方法(字符串操作)

发布于 2024-08-30 08:03:09 字数 514 浏览 5 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

许仙没带伞 2024-09-06 08:03:09

String.delete 方法(记录在此处 ) 将其参数视为数组,然后根据其数组的交集删除字符。

两个数组的交集是两个数组共有的所有字符。因此,您最初删除的 gone.delete!("o", "rv") 将变为

gone.delete ['o'] & ['r','s','t','u','v']

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 become

gone.delete ['o'] & ['r','s','t','u','v']

There are no characters present in both arrays so the deletion would get an empty array, hence no characters are deleted.

等数载,海棠开 2024-09-06 08:03:09

我更改

gone.delete!("o", "r-v")

gone.delete!("or-v")

并且效果很好。

I changed

gone.delete!("o", "r-v")

to

gone.delete!("or-v")

and it works fine.

紫竹語嫣☆ 2024-09-06 08:03:09

您使用不同的方式获得相同的o/p,例如 gsub

puts "deleted: " + gone.gsub('o', '')

o/ p

deleted: Got gone fool!

You get same o/p using some different way like gsub

puts "deleted: " + gone.gsub('o', '')

o/p

deleted: Got gone fool!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文