In the previous post I reviewed the history, and some basic elements about ruby like Symbols , visibility scope, comments. Today I’d like to start with variables declaration, following is the convention
- THIS_IS_A_CONSTANT
- $global_variable
- @@class_variable
- @instance_variable
- local_variable
This convention must be followed when you create
- methodForSomething
- ClassName
Let’s move on to Control Structures
CONDITIONALS
if x < 10
# do something
elsif x > 10
# do something
else
# do something
end
Please note that it’s not elseif, nor else if, it’s **elsif **
There’s also another option which evaluates to false, the opposite of if: unless
unless x < 10
# do something
else
# do something
end
#there's no elseunless, or something like that
But the beauty of Ruby doesn’t stop there, you can create inline sentence in the most delightful way (This is supposedly taken from PERL)
young = "i'm 10 years old" if x == 10
old = 'i'm very old' unless x < 70
As you can see, ruby is an straightforward language to read; a command line can be read as a sentence. Basically, to me, it’s an elegant and human-like way to talk with the program
LOOPS
The basic loop can be constructed with while or until
while x <= 10 do
puts "I'm "+x+" years old"
end
# the inverse
until x > 10 do
puts "I'm still a kid"
end
You can also use them as modifiers, just like if or unless described previously
The following syntax applies to basic instructions, if you want to code something more elaborated you must use the previous syntax
puts x = x+1 while x <= 10
# the inverse
puts x = x+1 until x > 10
To iterate through an array we can use the for loop
for value in collection
puts "this is the current #{value}"
end
# how to get key/value from an array
for key, value in array
puts "the value of #{key} is #{value}"
end
In the following post I’ll show you the advanced iterators. I hope these posts are helpful :)