From: Gennady Bystritsky Date: 2013-04-20T13:33:52+09:00 Subject: Re: String index produces unanticipated result --Apple-Mail=_9274C177-1471-4F11-9949-7BE2A712ABAB Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=iso-8859-1 On Apr 18, 2013, at 7:15 AM, Robert Klemme = wrote: >=20 >=20 >=20 > On Wed, Apr 17, 2013 at 10:41 PM, Thomas Luedeke = wrote: > Thanks. I am running Ruby 1.8.7. That would explain why online irb = gave > me what I expected. >=20 > What I used that worked was line[0..4].strip[0..0]. Makes me cringe, > but it does work. >=20 > Why then don't you do something like this: >=20 > irb(main):005:0> s=3D" 9 3 3 0 0" > =3D> " 9 3 3 0 0" > irb(main):006:0> s.scan(/\d+/).map(&:to_i)[0, 5].include? 9 > =3D> true >=20 > For 1.8 >=20 > irb(main):007:0> s.scan(/\d+/).map {|m| m.to_i}[0, 5].include? 9 > =3D> true Ruby 1.8.7 supports &:block syntax, apparently back ported from 1.9: irb(main):001:0> RUBY_VERSION =3D> "1.8.7" irb(main):002:0> [ 1, 2, 3 ].map(&:to_s) =3D> ["1", "2", "3"] >=20 > Or, with a regex >=20 > irb(main):009:0> /\A\s*(?:\d+\s+){0,4}9\D/ =3D~ s > =3D> 0 >=20 > Kind regards >=20 > robert >=20 >=20 > --=20 > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ --Apple-Mail=_9274C177-1471-4F11-9949-7BE2A712ABAB Content-Transfer-Encoding: 7bit Content-Type: text/html; charset=iso-8859-1
On Apr 18, 2013, at 7:15 AM, Robert Klemme <shortcutter@googlemail.com> wrote:




On Wed, Apr 17, 2013 at 10:41 PM, Thomas Luedeke <lists@ruby-forum.com> wrote:
Thanks. I am running Ruby 1.8.7.  That would explain why online irb gave
me what I expected.

What I used that worked was line[0..4].strip[0..0].   Makes me cringe,
but it does work.

Why then don't you do something like this:

irb(main):005:0> s="    9    3    3    0    0"
=> "    9    3    3    0    0"
irb(main):006:0> s.scan(/\d+/).map(&:to_i)[0, 5].include? 9
=> true

For 1.8

irb(main):007:0> s.scan(/\d+/).map {|m| m.to_i}[0, 5].include? 9
=> true

Ruby 1.8.7 supports &:block syntax, apparently back ported from 1.9:

irb(main):001:0> RUBY_VERSION
=> "1.8.7"
irb(main):002:0> [ 1, 2, 3 ].map(&:to_s)
=> ["1", "2", "3"]


Or, with a regex

irb(main):009:0> /\A\s*(?:\d+\s+){0,4}9\D/ =~ s
=> 0

Kind regards

robert


--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

--Apple-Mail=_9274C177-1471-4F11-9949-7BE2A712ABAB--