Hi,
I want to delete the numbers in a string, for example,
x=“abcd1234”
I have two ways:
x.gsub! /\d+/,""
x[/\d+/]=""
Which one is better?
I personally prefer the second one.
Thanks.
Hi,
I want to delete the numbers in a string, for example,
x=“abcd1234”
I have two ways:
x.gsub! /\d+/,""
x[/\d+/]=""
Which one is better?
I personally prefer the second one.
Thanks.
On Wed, Dec 9, 2009 at 11:10 AM, Ruby N. [email protected]
wrote:
x.gsub! /\d+/,“”
x[/\d+/]=“”
try also String#delete
On Dec 8, 2009, at 11:40 PM, Ruby N. wrote:
x[/\d+/]=""
Which one is better?
I personally prefer the second one.
The first. It doesn’t fail if the string contains no numbers:
x =“abcd”
x[/\d+/]=""
IndexError: regexp not matched
from (irb):10:in []=' from (irb):10 from /usr/local/bin/irb19:12:in
’
Regards,
Florian
2009/12/9 Florian G. [email protected]:
x =“abcd”
x[/\d+/]=“”
IndexError: regexp not matched
from (irb):10:in[]=' from (irb):10 from /usr/local/bin/irb19:12:in
’
And then there’s also
irb(main):001:0> “123ab”.tr “0-9”, “”
=> “ab”
irb(main):002:0> “123ab”.tr! “0-9”, “”
=> “ab”
Cheers
robert
2009/12/10 Wybo D. [email protected]:
irb
$-w=true
=> true
“abcd1234”.gsub! /\d+/,‘’
(irb):13: warning: ambiguous first argument; put parentheses or even spaces
=> “abcd”
“123ab”.tr! “0-9”,“”
=> “ab”what is the ambiguity in the first case, and why is there no warning in the
second case?
Seems to be related to the regexp:
10:56:19 $ ruby19 -wce ‘o.gsub! /\d/, “”’
-e:1: warning: ambiguous first argument; put parentheses or even spaces
Syntax OK
10:56:42 $ ruby19 -wce ‘o.gsub! “d”, “”’
Syntax OK
10:56:50 $ ruby19 -wce ‘o.gsub!(/\d/, “”)’
Syntax OK
10:57:01 $
Why? No idea.
Cheers
robert
Robert K. wrote:
And then there’s also
irb(main):001:0> “123ab”.tr “0-9”, “”
=> “ab”
irb(main):002:0> “123ab”.tr! “0-9”, “”
=> “ab”
But why no parentheses?:
irb
$-w=true
=> true“abcd1234”.gsub! /\d+/,’’
(irb):13: warning: ambiguous first argument; put parentheses or even
spaces
=> “abcd”“123ab”.tr! “0-9”,""
=> “ab”
what is the ambiguity in the first case, and why is there no warning in
the
second case?
Hi,
Am Donnerstag, 10. Dez 2009, 18:58:04 +0900 schrieb Robert K.:
=> “ab”
Syntax OK
10:56:50 $ ruby19 -wce ‘o.gsub!(/\d/, “”)’
Syntax OK
10:57:01 $Why? No idea.
The slash could also be a division operator. Say:
$ ruby -wce ‘o.gsub! %r/\d/, “”’
$ ruby -wce ‘o.gsub! %r{\d}, “”’
Bertram
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs