Forum: Ruby Subtracting strings

Posted by John Sampson (Guest)
on 2012-12-20 19:11
(Received via mailing list)
Is there a method for deleting a string identified in a variable from
another string, e.g.

<rubycode>
myunwantedword = "Hello"
myphrase = "Hello world"
output = myphrase.suchamethod(myunwantedword)
</rubycode>

output is now " world"

Regards

_John Sampson_
Posted by Ricky Ng (Guest)
on 2012-12-20 19:20
(Received via mailing list)
a = "hello world"
b = "hello "
a.sub!(b, "")

Is what I usually end up using. Hopefully I get corrected with a cleaner
way.
Posted by Calvin B. (calvin_b)
on 2012-12-20 19:22
(Received via mailing list)
Hello,

yes, there is (two, actually). They are called String#gsub and
String#gsub!, respectively.

Regards
Posted by John Sampson (Guest)
on 2012-12-20 21:45
(Received via mailing list)
On 20/12/2012 18:22, Calvin Bornhofen wrote:
> Hello,
>
> yes, there is (two, actually). They are called String#gsub and
> String#gsub!, respectively.
>
> Regards
>
>
>
Many thanks - I did not know one could have a variable as an argument
for sub or sub!

Regards

_John S_
Posted by 7stud -- (7stud)
on 2012-12-21 02:29
John Sampson wrote in post #1089759:
> On 20/12/2012 18:22, Calvin Bornhofen wrote:
>> Hello,
>>
>> yes, there is (two, actually). They are called String#gsub and
>> String#gsub!, respectively.
>>
>> Regards
>>
>>
>>
> Many thanks - I did not know one could have a variable as an argument
>

Any place a literal, e.g. 10, 'hello', [1, 2, 3], can be used, a 
variable
containing one of those values can be used in its place.
Posted by Brian Candler (candlerb)
on 2012-12-21 16:53
Another way, if you only want to remove the first instance:

>> myunwantedword = "Hello"
=> "Hello"
>> myphrase = "Hello world"
=> "Hello world"
>> output = myphrase.dup
=> "Hello world"
>> output[myunwantedword] = ""
=> ""
>> output
=> " world"
>>

Or you can use slice! instead of []=

>> output.slice!(myunwantedword)
=> "Hello"
>> output
=> " world"
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.