[#4567] Re: What's the biggest Ruby development? — Aleksi Niemel<aleksi.niemela@...>

Dave said:

18 messages 2000/08/23
[#4568] Q's on Marshal — Robert Feldt <feldt@...> 2000/08/23

[#4580] RubyUnit testcase run for different init params? — Robert Feldt <feldt@...> 2000/08/25

[#4584] Re: RubyUnit testcase run for different init params? — Dave Thomas <Dave@...> 2000/08/25

Robert Feldt <feldt@ce.chalmers.se> writes:

[#4623] Re: RubyUnit testcase run for different init params? — Robert Feldt <feldt@...> 2000/08/28

On Sat, 26 Aug 2000, Dave Thomas wrote:

[#4652] Andy and Dave's European Tour 2000 — Dave Thomas <Dave@...>

24 messages 2000/08/30
[#4653] Re: Andy and Dave's European Tour 2000 — matz@... (Yukihiro Matsumoto) 2000/08/30

Hi,

[#4657] Ruby tutorials for newbie — Kevin Liang <kevin@...> 2000/08/30

Hi,

[ruby-talk:4602] Re: Getting list of regexp matches

From: Stephen White <steve@...>
Date: 2000-08-27 14:45:26 UTC
List: ruby-talk #4602
On Sun, 27 Aug 2000, Dave Thomas wrote:

> Having said that, this isn't really an iterator issue: we're using gsub to
> to the matching and the block attached to it to accumulate the results.

Thanks for the help. By combining this message (some nice tricks in your
code!) with your article on object oriented regexps, I came up with this.

  #! /usr/local/bin/ruby
    		 
  a = File.new("a").read(nil)
  table = Hash.new

  pattern = /(new|table|end)/

  a.scan(pattern) {|i|
    table[i] ||= []   
    table[i] += $~.begin(0)
  }
     
  puts table.inspect

which produces the following result:

  {["new"]=>[33, 65, 82], ["table"]=>[52, 86, 122, 140, 172], ["end"]=>[92]}

It doesn't iterate through the regexps, but at least it does get called for
every regexp match so I can access the intermediate values.

First observation was that the first way I tried it:

  for i in a.scan(pattern)
    table[i] ||= []   
    table[i] += $~.begin(0)
  end

doesn't allow access to the intermediate regexp values, so there's a
difference between {} and for..end. I thought it was syntaxic sugar?

Second observation is that "nil + []" results in an error, instead of just
"[]" as expected. I had to borrow your nifty trick of doing "||= []" to make
sure there was an array, instead of being able to do

  a.scan(pattern) {|i|
    table[i] += [ $~.begin(0) ]
  }

Any reason why "nil + []" should result in an error, or could this be a
small touchup for the library?

I'm enjoying Ruby. Perl and Python didn't excite me enough for me to expend
the effort to learn them, but Ruby keeps me glued to the computer.

Thanks for the help. :)

--
  steve@deaf.org


In This Thread