|Getting Started With Ruby - A Functional Language|
|Written by Mike James|
|Wednesday, 03 April 2013|
Page 3 of 3
Reflection and metaprogramming
You might have noticed the use of the eval method in the last few examples.
Ruby supports code examination, modification and creation at run time. The documentation refers to this as reflection and metaprogramming and indeed if you keep it under control it can be this well organized but the fact of the matter is that this is a slippery slope to self-modifying code which is generally not a good idea.
The problem is that while it seems to have protective mechanisms in reality it provides you with more than enough rope to tie a knot.
But used carefully then it can be a powerful way to implement something that otherwise would be very complicated. Use reflection and metaprogramming to make things simple not complex.
What more do you need to find out about?
The main things that make Ruby different are the use of the block to pass custom code to methods. This makes creating and using iterators easy. Once you know this then the fact that loops don't play a big part in Ruby code seems natural. To see how this works in more detail you need to take a look at Ruby's data structures both the array and the hash.
If you look at your Ruby program and it has lots of for and while loops then you are probably not making best use of Ruby. Natural Ruby style tends to prefer collection method calls to loops.
The three main operating principles of Ruby are that:
Most of what you encounter in Ruby that is different fits into one of these categories. Things that are common that might confuse includes the ability to write conditionals "backwards". As well as if there is an Unless which only executes the then clause if the condition is false. So, for example:
only adds one is i is less than or equal to 10. You can also write if and unless modifiers to the end of any expression (Perl style). So you can write:
You can see that for a programmer more familiar with the simple if..then..else this can quickly become confusing. However, it is the more usual way of expressing conditionals in natural language.
Also you need to know about lazy enumerations introduced in Ruby 2, but this is a more advanced topic and it can probably wait.
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: email@example.com
|Last Updated ( Wednesday, 03 April 2013 )|