Forum: Ruby regualr expression question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A70fa59bf5a0721cf06654e573434a93?d=identicon&s=25 Reg (Guest)
on 2009-04-17 00:40
(Received via mailing list)
The "Ruby_RegularExpression" sample application in the
javapassion rubyonrails tutorial has this code

puts "----Regular Expression"
puts   a = "hello there"
puts   a[1]                   #=> 101
puts   a[1,3]                 #=> "ell"

How do you get 101 from a[1]
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2009-04-17 01:04
(Received via mailing list)
On Apr 16, 2009, at 6:40 PM, Reg wrote:

> The "Ruby_RegularExpression" sample application in the
> javapassion rubyonrails tutorial has this code
>
> puts "----Regular Expression"
> puts   a = "hello there"
> puts   a[1]                   #=> 101
> puts   a[1,3]                 #=> "ell"
>
> How do you get 101 from a[1]

It's the value associated with the character e in ASCII.

In irb:

 > RUBY_VERSION
=> "1.8.6"
 >> a = 'hello'
=> "hello"
 >> a[1]
=> 101
 >> ?e
=> 101
 >> a[1 ,1]
=> "e"
 >>


If you look at the ri documnetation for String#[] in Ruby 1.8.6 you
can see:

-------------------------------------------------------------- String#[]
      str[fixnum]                 => fixnum or nil
      str[fixnum, fixnum]         => new_str or nil
      str[range]                  => new_str or nil
      str[regexp]                 => new_str or nil
      str[regexp, fixnum]         => new_str or nil
      str[other_str]              => new_str or nil
[...]
------------------------------------------------------------------------
      Element Reference---If passed a single +Fixnum+, returns the code
      of the character at that position.
[...]

In Ruby 1.9 things change so that you always get a String or nil back
from String#[]:

irb(main):001:0> RUBY_VERSION
=> "1.9.2"
irb(main):002:0> a = 'hello'
=> "hello"
irb(main):003:0> a[1]
=> "e"
irb(main):004:0>

Hope this helps,

Mike

--

Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
A70fa59bf5a0721cf06654e573434a93?d=identicon&s=25 Reg (Guest)
on 2009-04-17 01:26
(Received via mailing list)
On Thu, 16 Apr 2009 18:02:52 -0500, Mike Stok <mike@stok.ca> wrote:


> >> a[1]
>
>      of the character at that position.
>=> "e"
>irb(main):004:0>
>
>Hope this helps,
>
>Mike

Its a great help!
Thanks Mike
This topic is locked and can not be replied to.