Forum: Ruby Subtracting strings

17dde2088ab780b02adda37dfeeda037?d=identicon&s=25 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_
20753db11b9ffec13351e7fc2ddfbf7e?d=identicon&s=25 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.
45441e46d19d428be152ecb81883044a?d=identicon&s=25 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
17dde2088ab780b02adda37dfeeda037?d=identicon&s=25 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_
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 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.
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 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

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.