[#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:4593] Re: Getting list of regexp matches

From: Dave Thomas <Dave@...>
Date: 2000-08-26 21:32:00 UTC
List: ruby-talk #4593
Stephen White <steve@deaf.org> writes:

> I don't quite understand the concept of iterators. Let's say I have an array
> of regexp's containing keywords, like:
> 
>   keywords = [ /int/, /float/, /double/ ]
> 
> then I have a file in variable, like:
> 
>   a = File.new("freddie.c").read(nil)
> 
> I can understand how to use iterators to go through the keywords array, but
> not how to get an array of matches.
> 
> What I'd like out of this is a list of matches, like:
> 
>  [ "int",    [ 56, 78, 128 ],
>    "float",  [ 90, 400 ],
>    "double", [ 200, 250 } }
> 
> Is Ruby capable of iterating through regexp matches, or do I have to restart
> regexp for every match, which is wasteful of resources?

Yup -- not really a problem, particularly if you don't mind having the 
result come back in a hash, rather than an array. 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.

I'm not sure what the numbers in your result are: let's assume line
numbers:

  keywords = /\b(int|float|double)\b/

  result = Hash.new

  IO.foreach("freddie.c") do |line|
    line.gsub(keywords) { |kw| result[kw] ||= []; result[kw].push $. }
  end

  result.each { |kw, lines| print "#{kw}: #{ lines.join(', ')}\n" }


Feed it freddie.c:

     int i;
     double d;
     float f(int j, double k) {
       int l;
       notint k;
     }

And you get:

     int: 1, 3, 4
     float: 3
     double: 2, 3


Regards


Dave

In This Thread