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_
on 2012-12-20 19:11
on 2012-12-20 19:20
a = "hello world" b = "hello " a.sub!(b, "") Is what I usually end up using. Hopefully I get corrected with a cleaner way.
on 2012-12-20 19:22
Hello, yes, there is (two, actually). They are called String#gsub and String#gsub!, respectively. Regards
on 2012-12-20 21:45
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_
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.
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
Log in with Google account | Log in with Yahoo account
No account? Register here.