hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Hal's if..each #

by why in bits

I’m contemplating putting a difficulty level on posts in the “bits” and “inspect” sections. A simple rating of 1 to 5. I’d consider the following code to be an even 3. These kinds of examples are the sweet spot for moving past beginner.

It’s at this stage that you’re familiar enough to chain Ruby constructs together creatively. Every Ruby construct returns a value of some kind. How can that return be used?

Hal Fulton’s if..each uses each to loop through a list unless the list is empty and check the list for emptiness. In which case the second bit of code (which prints "no songs!") is executed.

 if song_list.each do |song|
   print song.name
 end.empty?
   print "no songs!" 
 end

The fragment is made tricky because the indentation fools you. Sky punchers have the advantage here. (found in for..in..else? Please note that Hal’s was originally an unless..each but testing revealed that if..each is the correct.)

Comments are closed for this entry.