Feel free to delete this topic if it's discussed or quite obvious. I hail from C# background and I'm planning to learn Ruby. Everything I read about it seems quite intriguing. But I'm confused over this basic philosophy of Ruby that "there's more than one way to do one thing". Can someone provide 2 or 3 simple arithmetic or string examples to make this point clear, like if its about the syntaxes or logics etc.
Thanks
"More than one way of doing something" means having the choice of doing something the way you want it. That way you can use various programming styles, no matter what background you're coming from.
Iteration using
forvs. blocksYou can iterate over an array of things like so. This is pretty basic, and if you're from a Java background, this feels kind of natural.
A more Ruby-like way would be the following:
The first is a rather well known way of doing things. The second one is using blocks, a very powerful concept that you'll find in many Ruby idioms. Basically, the array knows how to iterate over its contents, so you can modify this and add something like:
You could have done it like this too, but now you see that the above one looks easier:
Passing arguments as usual or using
HashesNormally, you would pass arguments like so:
However, you may also use a Hash to do that:
The second form is one used excessively by Ruby on Rails. The nice thing is that you now have named parameters. When you are passing them, you will more easily remember what they are used for.