[Basic question] why a number does not match regular expression which represents a number?

Hi

C:\Users\bdimych>
C:\Users\bdimych>
C:\Users\bdimych>irb
irb(main):001:0> RUBY_VERSION
=> “1.9.2”
irb(main):002:0> x = 111
=> 111
irb(main):003:0> x =~ /\d/
=> nil
irb(main):004:0>

It was unexpected for me, I thought since Ruby is dynamically typed it
should handle such thing implicitly. Is this described in
documentation?

Bdimych B. wrote in post #1048291:

Hi

C:\Users\bdimych>
C:\Users\bdimych>
C:\Users\bdimych>irb
irb(main):001:0> RUBY_VERSION
=> “1.9.2”
irb(main):002:0> x = 111
=> 111
irb(main):003:0> x =~ /\d/
=> nil
irb(main):004:0>

It was unexpected for me, I thought since Ruby is dynamically typed it
should handle such thing implicitly. Is this described in
documentation?

Being dynamically typed is not the same as automatically converting one
type to another. In Ruby, “0” and 0 are two completely different
objects.

However the case in point here also highlights something else: operators
in ruby are just syntactic sugar for method calls. a =~ b is really
a.=~(b)

Now note:

/\d/ =~ 111
TypeError: can’t convert Fixnum into String
from (irb):2

111 =~ /\d/
=> false

The first is calling Regexp#=~ which requires a string as its argument,
which is sensible. So really the question is, why does Fixnum#=~ exist
at all?

Object.new =~ /\d/
=> false

So it appears it has inherited this from Object#=~. I’m not really sure
why Object has such a method, and it seems to be more a source of
confusion than anything, but it is documented:

http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-3D-7E

Ruby can do argument type coercion(for example: integer => float), but
in the case of x =~ /\d/ which is really just ‘x.=~(/\d/)’, what do you
think a regex expression such like ‘/\d/’ to be converted to?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs