Learning Ruby: Syntax (Part 1)
I’ve meaning to learn Ruby for some time now.
Especially, when I dabbled from time to time in Elixir, I felt that knowing Ruby may be an advantage (since Elixir syntax similar to Ruby)
No one learns (I think) Ruby just for the language. They learn it so that they can use Ruby on Rails (RoR as popularly known) RoR, in case you don’t know, is the Web framework. Like Django in Python land. But there are a lot of web frameworks like Flask, Pyramid, FastAPI to name some.
I know of Sinatra - I think it is like Flask, but I could be wrong.
Rails seems to have great documentation.
Ruby on the other hand, sends you to third party sources, at least one of them no longer exist or unreachable.
I started with Learn X in Y minutes. This is a great place to get familiar with syntax.
I understand that knowing the syntax is just the first step. Step that must be taken before knowing more.
Coming from Python, here are some of the differences I noticed.
- Python has no concept of
Symbols
(In Elixir these areAtoms
) - Arithmetic functions are just method invoking a method.
1.+(3) #=> 4
10.* 5 #=> 50
Luckily, we don’t have to always use this awkward method. Normal 1+3
also works 😆
- Special Values too are objects
nil.class #=> NilClass
true.class #=> TrueClass
false.class #=> FalseClass
%w
seems useful. Less typing - more developer productivity !!
%w[foo bar baz] #=> ["foo", "bar", "baz"]
- Array are like Python
list
- Hashes are like Python dictionary, but slight different syntax
# Hashes are Ruby's primary dictionary with key/value pairs.
hash = { 'color' => 'green', 'number' => 5 }
- But when using Symbols for keys, python-like syntax can be used
hash = { :defcon => 3, :action => true }
hash.keys #=> [:defcon, :action]
hash = { defcon: 3, action: true }
hash.keys #=> [:defcon, :action]
more tomorrow … 💤