On Sun, Sep 27, 2009 at 3:20 PM, Thairuby ->a, b {a + b} <
kabkab / doramail.com> wrote:

> Thairuby ->a, b {a + b} wrote:
> > Is this ok? But it still use variable :(
> >
> > file.each_line { |line|
> >   if line =~ (a ||= $line_patterns["pattern a"])
> >     process_pattern_a(line)
> >   elsif line =~ (b ||= $line_patterns["pattern b"])
> >     process_pattern_b(line)
> >   # some more elsifs
> >   end
> > }
>
> I'm wrong typing. It would be
>
> file.each_line { |line|
>  if line =~ (a ||= /^pattern[a]*/)
>    process_pattern_a(line)
>  elsif line =~ (b ||= /pat+e(rn)? b\s*$/)
>     process_pattern_b(line)
>  # some more elsifs
>  end
> }
>
> Does it have o option for string? :)
> --
> Posted via http://www.ruby-forum.com/.
>
>
Unfortunately, I don't think this does anything, because a and b are
declared within the block, so while the scope is the same, the extent is
not. Essentially, a and b are no longer bound, after each iteration of the
loop. So upon entering each iteration, they do not retain their previously
assigned values.

This can be illustrated:

"patterna\npatte b".each_line do |line|

  p line

  puts "defined?(a) => #{defined?(a).inspect}"
  puts "defined?(b) => #{defined?(b).inspect}"

  if line =~ (a ||= /^pattern[a]*/)
  elsif line =~ (b ||= /pat+e(rn)? b\s*$/)
  else
  end

  puts "defined?(a) => #{defined?(a).inspect}"
  puts "defined?(b) => #{defined?(b).inspect}" , ''

end
__END__

Which has the following output:
"patterna\n"
defined?(a) => nil
defined?(b) => nil
defined?(a) => "local-variable(in-block)"
defined?(b) => "local-variable(in-block)"

"patte b"
defined?(a) => nil
defined?(b) => nil
defined?(a) => "local-variable(in-block)"
defined?(b) => "local-variable(in-block)"

You can see, that a and b were defined after the if statement in "patterna",
but were no longer defined before the if statement for "patte b"