Learning Ruby: Syntax (Part 2)
Learning continues …
- idiomatic(?) ruby loops use
each
like :
(1..5).each do |counter|
puts "iteration #{counter}"
end
Although python like loop also work
for counter in 1..5
puts "iteration #{counter}"
end
-
array.each_with_index
is like python’senumerate
-
Ruby seems to have multiple ways to do the same thing, as opposed to Python’s
There should be one– and preferably only one –obvious way to do it.
e.g. a.map do .. end
, a.map { |el| e.something }
and a.map(&:method)
➜ cat test.rb
array = [1,2,3,4,5]
sqr = array.map do |item|
item * item
end
puts sqr
a = ["Foo", "bAr", "baZ"]
puts a.map { |s| s.downcase }
puts a.map(&:upcase)
mandar in /tmp via 💎 v3.1.0
➜ ruby test.rb
1
4
9
16
25
foo
bar
baz
FOO
BAR
BAZ
-
Python did not have
case
statement, till 3.10 introduced Structural Pattern Matching -
Exception handling has different keywords, but parallels exist in Python world
Python | Ruby |
---|---|
try | begin/end |
except | rescue |
else | else |
ensure | finally |
-
Python requires explicit return, else it returns
None
by default. Ruby on the other hand implicitly return the value of the last statement. (This was not a surprise to me since Elixir also does the same.) -
yield
is different in Ruby compared to Python. I haven’t fully groked Ruby’syield
. It seems like a placeholder, but I could be wrong. Need to dig deeper to understand.