简体   繁体   English

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

[英]Ruby delete method (string manipulation)

I'm new to Ruby, and have been working my way through Mr Neighborly's Humble Little Ruby Guide. 我是Ruby的新手,并且一直在通过Mr. Neighborly的Humble Little Ruby指南工作。 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): 这是非常基本的,但我无法在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? 任何人都可以对这里出了什么问题有所了解吗? :-\\ : - \\

The String.delete method ( Documented here ) treats its arguments as arrays and then deletes characters based upon the intersection of its arrays. String.delete方法( 此处记录 )将其参数视为数组,然后根据其数组的交集删除字符。

The intersection of 2 arrays is all characters that are common to both arrays. 2个数组的交集是两个数组共有的所有字符。 So your original delete of gone.delete!("o", "rv") would become 所以你原来删除了gone.delete!("o", "rv")就会变成

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. 两个数组中都没有字符,因此删除将获得一个空数组,因此不会删除任何字符。

I changed 我变了

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

to

gone.delete!("or-v")

and it works fine. 它工作正常。

You get same o/p using some different way like gsub 你可以使用像gsub这样的不同方式获得相同的o / p

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

o/p O / P

deleted: Got gone fool!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM