The following is a guest post by Jack Nolan and originally appeared on his blog. Jack is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.
The easie of which ruby allow me to iterate over an collection without having to worry about the mundane details is amazing. Need to find the total of an array of prices? Here is inject to help!
4) blocks / yield
The power of ruby is staggering and it starts at the block. Lets take an example I used the other day. I need to highlight certain output so in order to remain DRY I created this function.
Send allows you to call a method from the name of the method. This allows you to be flexible with your code and in a lot of places remain dry. Lets consider you have to initialize an object and set five fields money,age,happiness,height and weight all to 9001 we could do it like this.
Or we could save ourselves some typing and use our send method
note: This become incredibly powerful (and cool) when combined with introspection but thats another whole other post.
Allowing you to define instance methods of a class on the fly. This has amazing power in allowing you to refactor code and create some cool tools. For example we coulde create our own attr_accessor function.
There is a lot going on here. The define_method method gets called twice once to create a method named
name and once to create a method named
name=. These then use some methods build into the Object class to act as a getter and setter.
This method gets called when a method is undefined and could allow you to define it or provide a custom response. So if we wanted to we could create a very forgiving interface for an object.
These are just 5 things that when I first ran into them I had one of those “ahh thats cool” moments which made me <3 ruby.
Make yourself useful.