I can't seem to escape Rails. Everybody keeps talking about while I plug away at Django. I need to see what all the fuss is about so I'm going to start learning Ruby. As Python guy, I feel like I'm being a little unfaithful to my first true programming language (I'm not counting PHP and Javascript). It has been so good to me but I can't get attached to tools. Ruby and Python are just mediums to do creative things.
I learn best when I document stuff (hence this blog). So I'm going to write some notes on Ruby as I learn it. I already dabbled Ruby before, but I am far from good at it. I can't bang Ruby code out like I can Python.
The following is basically going to be a stream-of-consciousness documentation of what I'm learning.
The syntax between Python and Ruby are very similar. Lots of stuff is pretty much the same.
Ruby has something called symbols that look like this:
They are like strings, but they are immutable. In Python, strings are already immutable.
Ruby has constants. I really like this. It's a normal variable, but Ruby complains when you try and change it. Python doesn't have that (at least not that I know of). So, I could do something like
and if my program changes the value of Pi, Ruby will tell me.
To create a global variable in Ruby, you use the dollar sign.
In Python, you would use the global keyword.
Instance variables begin with @ in Ruby. In Python we use self.
Ruby uses curly braces for blocks of code.
This is nice as I think even non-programmers can understand what this does. In Python I would do
That looks a bit more cryptic.
Block arguments are surrounded by pipe characters and are used in the beginnings of blocks.
Ranges in Ruby look like this (1..5) or for characters ('a'..'z')
If you wish to omit the last value in the range, you include another dot: (1...5)
Arrays in Ruby seem to be the same things as lists in Python. They have similar methods and they both keep elements in a specific order.
Hashes are like dictionaries in Python. The syntax for creating a hash is slightly different from creating a dictionary in Python. Hashes can have strings or symbols for keys. In Ruby could do
or
or
That seems really unnecessary.
I can use regular expressions in Ruby without importing a library. All I have to do is surround them in slashes like this.
Nice.
So to find a digit, I can do
Python is a bit more involved.
Ruby's nil is like Python's None.
This is really nifty:
To do the same thing in Python, I would have to type wearing_tie twice.