[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:04162] Re: Regex question

From: Dave Thomas <Dave@...>
Date: 2000-07-21 17:26:59 UTC
List: ruby-talk #4162
hal9000@hypermetrics.com writes:

> The program here is totally frivolous -- it prints out the
> obnoxious drinking song "99 Bottles of Beer on the Wall."
> 
> But the regex question is real. I'm not doing the substituting
> the "proper" way -- a block with \1 \2 and so on.

In the block, you can use $1, $2. In a substitution string, \1, \2.

So

   a = "aardvark"
   a.gsub(/a(.)(.)/, '\2a\1')
   a.gsub(/a(.)(.)/) { "#{$2}a#$1" }

However, you can also chain subs and the like:

     class Inebriation
       Verse = <<-EOV .gsub(/^\s+/, '')
         N bottles of beer on the wall,
         N bottles of beer;
         Take one down and pass it around,
         M bottles of beer on the wall!
       EOV

       def drink(*brew)
         brew.each do |x|
           cold_one = Verse.gsub(/N/, x.to_s).
                            sub(/M/,  (x-1).to_s).
                            gsub(/1 bottles/, '1 bottle')
           puts cold_one, "\n"
         end
       end
     end

     blitzkrieg = Inebriation.new
     beer=(1..9).to_a.reverse!
     blitzkrieg.drink *beer


Regdsda3vds

adev

In This Thread