Thank you for visiting my blog. Here is my latest blog: https://yedhu.me.
You will find my newer posts here, and I've moved some of my old posts from this blog to my new one.
My (archived) blog to share what I learn. See my newer posts here: https://yedhu.me
Thank you for visiting my blog. Here is my latest blog: https://yedhu.me.
You will find my newer posts here, and I've moved some of my old posts from this blog to my new one.
ruby your_script.rb
From there, it is a walkthrough on how ruby reads, tokenises, parses and compiles the program into something the underlying Ruby Virtual Machine understands. For me, this was a pragmatic recap of compiler theory from my college days. What I learned then was just theory. Here, Pat shows the actual source code which does what is meant to be done! I got a new perspective on the basic concepts like tokenising and grammar parsing just by reading the first chapter. This book gave me courage to go through the actual ruby source code written in C!defmodule TowerOfHanoi do def move(1, source, destination, intermediate) do IO.puts ["Move ", source, " to ", destination] end def move(no_of_disks, source, destination, intermediate) do move(no_of_disks - 1, source, intermediate, destination) IO.puts ["Move ", source, " to ", destination] move(no_of_disks - 1, intermediate, destination, source) end end
for(i = 0; i < 5; i++) {
sum = sum + i;
}
Here we are modifying (mutating) the value of i as well as sum in each interation. Mutation is considered as a bad practice and functional programming languages do not encourage it. Let's see some basic examples of recursion in Elixir.defmodule Recursion do
def print_hello(n) when n <= 1 do
IO.puts "hello"
end
def print_hello(n) do
IO.puts "hello"
print_hello(n - 1)
end
end
Recursion.print_hello("Hello!", 3)
# Hello!
# Hello!
# Hello!
Here, defmodule is used to define a module (group of several functions). We can have multiple definitions of the same function. In the first function when n <= 1 is a guard. This function will get executed only when the guard condition is satisfied (no wonder why it is called a guard!). When there are multiple clauses (definitions) of the same function, Elixir looks for a match and executes it when it finds one. If no matches are found, it will throw error.iex> string = "hełło"
"hełło"
iex> byte_size string
7
iex> String.length string
5
Here, we can see that the byte size of the string is 7 while the string length is 5. The function byte_size/1 can be used to check how many bytes are actually used in the memory to represent the given string.