The ‘if’ Statement

As stated in the past post, we aim to simplify further the code we have just created with the following shorter version of the same program.

class BookList
def [](key)
if key.kind_of?(integer)
result = @Books[key]
else
result = @Books.find { |aBooks| key == sBooks.name}
end
return result
end
end

Further shortening the code we have above by using the ‘if’ statement as a modifier it becomes a shorter version of its former self as:

class Booklist
def [](key)
return @Books[key] if key.kind_of?(Integer)
return @Books.find { |aBooks| aBooks.name == key }
end
end

The use of the ‘find’ command in Ruby is simply a call to a function that is executed and it can be compared to a block call in many other languages such as Perl, C++ or Java.

This entry was posted in Development, Programming Basics and tagged , . Bookmark the permalink. Comments are closed, but you can leave a trackback: Trackback URL.

Bad Behavior has blocked 19 access attempts in the last 7 days.