Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #3554

Re: pattern matching and array methods

From Brian Candler <b.candler@pobox.com>
Newsgroups comp.lang.ruby
Subject Re: pattern matching and array methods
Date 2011-04-27 02:57 -0500
Organization Service de news de lacave.net
Message-ID <379e9ad9628af6f9972a8255e435d28d@ruby-forum.com> (permalink)
References <d4d716c8f8db27cf9490dd380e656a03@ruby-forum.com> <BANLkTikqzThxF5ufpz-VExi9DZ17LxTkiw@mail.gmail.com>

Show all headers | View raw


Dhruva Sagar wrote in post #995263:
> Something like this should do it :
>
> line.each {|l| puts l if l =~ /^(1:2)|(1:3)|(1:4)/}

That's a poor answer, because your regexp isn't anchored properly. It 
would match "5:6 abc1:3def" and "1:23 foobar" for example.

I suggest using the regexp to parse the line, then using numeric 
testing. This makes it easier to solve the other example of 3:9 to 3:31

lines.each do |line|
  if line =~ /^(\d+):(\d+)/
    major, minor = $1.to_i, $2.to_i
    puts line if major == 3 and (9..31).include?(minor)
  end
end

Note that you don't need to read the whole file in at once using 
readlines; you can read and process it one line at a time. This lets it 
work on huge files which are too big to fit into RAM.

File.open("...") do |file|
  file.each_line do |line|
    if line =~ ... as before
      ...
    end
  end
end

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

pattern matching and array methods Mfer Dez <emphxl@yahoo.com> - 2011-04-26 23:07 -0500
  Re: pattern matching and array methods Josh Cheek <josh.cheek@gmail.com> - 2011-04-26 23:27 -0500
    Re: pattern matching and array methods Josh Cheek <josh.cheek@gmail.com> - 2011-04-27 13:00 -0500
  Re: pattern matching and array methods Christopher Dicely <cmdicely@gmail.com> - 2011-04-27 00:19 -0500
  Re: pattern matching and array methods Dhruva Sagar <dhruva.sagar@gmail.com> - 2011-04-27 01:32 -0500
    Re: pattern matching and array methods Brian Candler <b.candler@pobox.com> - 2011-04-27 02:57 -0500
      Re: pattern matching and array methods Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-27 03:52 -0500
  Re: pattern matching and array methods 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-27 13:31 -0500

csiph-web