« Melksham Quiz | Main | Adding a member to a Hash in Ruby »

December 16, 2006

Ruby - Totally Topical

Ruby supports topicalisation - the $_ variable being set by certain statements when a piece of code such as gets in a while statement isn't assigned, and the the same variable being used in many other methods - and even as the object on which methods run by default - in following code.

Here's a piece of code that does NOT use topicalisation:

while info = DATA.gets
  iparts = info.split(/\s+/)
  next unless info =~ /Ruby/
  puts iparts[-1]
  end
__END__
Ruby is a great language
Python is a good language
Ruby is a type of gem
Python is a species of snake
Ruby is a colour
Woodland is a group of trees

And here is the same piece of code with the default input and pattern matching space left out everywhere that info occurred above. And split defaults to splitting at white space, so that can be simplified too.

while DATA.gets
  iparts = split
  next unless /Ruby/
  puts iparts[-1]
  end
__END__
Ruby is a great language
Python is a good language
Ruby is a type of gem
Python is a species of snake
Ruby is a colour
Woodland is a group of trees

Whichever way I run that:

grahamellis$ ruby gloop1
language
gem
colour
grahamellis$

Posted by gje at December 16, 2006 04:45 AM

Comments

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008