Ruby - Totally Topical
Archive - Originally posted on "The Horse's Mouth" - 2006-12-16 04:45:47 - Graham EllisRuby 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$