Getting started with Ruby – Part 4 – Hashes & Blocks

In my previous article Getting started with Ruby – Part 3 I started with Collections and covered basics of Ranges & Arrays. Like I mentioned towards the end of the article (in case you couldn’t manage to reach the end) I will start with one of the most commonly used Collection objects in Ruby, namely Hashes.

Hashes are essentially data structures to store key – value pairs, when you wish to store an element in the Hash you do so by assigning a unique key to it within the hash and while retrieving you do so with the help of that unique key. The beauty of hashes is the fact that the ‘key’ in question here could be just about any object in Ruby, most commonly however in practice strings or symbols (i’ll get to what these are soon) are used as keys.

Well i’ve said enough, time for some code :

That just about covers the basics of Hashes, which in turn covers the basics of various built-in data type classes in Ruby.

As per my previous article Getting started with Ruby – Part 3 I have to now get started with loops in Ruby. But before I get into that, I feel it is important that I introduce you to blocks. Blocks in Ruby are essentially nameless functions, in Ruby blocks are used extensively to achieve a lot of cool stuff.

For now I think that  good enough to go forward, later on we should come across more complex & advanced usages of blocks & closures.

An important point about functions, it is not mandatory to use brackets ‘(‘ & ‘)’  while calling a function for passing the arguments unless you’re calling a function within a function call as an argument or when you are passing a block to it

Considering that the article is already quite long and loaded with a whole lot to digest, I will now take up loops in my next part. I hope the article is easy to understand. If you have any questions or suggestions, please feel free to put them in the comments below and I will make sure I address it asap.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.