- Everything in Ruby is an Object (except blocks) and everything has methods.
- In Ruby,
{}
are generally interchangeable with the keywordsdo
andend
. - There is no method overloading, the last one declared is invoked, because it overrides the others.
- Instance variables (attributes) are trapped inside the instance and need to be published throught attribute accessors methods, for instance.
# Sigle line
=begin
Multi
line
comment
=end
- Ruby is case sensitive.
- Local variables are snake_cased.
Ruby has many methods that end with !
. Whenever you see !
, think: "This method may be dangerous and do something unexpected!" In many cases, the unexpected part is that the original variable gets changed, not a copy. In others cases, it's used when we're going to change something in the database.
As a general rule, Ruby methods that end with ?
evaluate to the boolean values true
or false
- Exponentiation:
**
print
takes whatever you give it and prints it to the screen without a new line.puts
prints to the screen and adds a newline. Invokes theto_s
method of the receiver.p
invokes theinspect
method of the receiver.
# These two lines are equivalent:
p an_object
puts an_object.inspect
gets
gets input from the user. Ruby adds a new blank line after each bit of input; gets.chomp
removes that extra line. Your program will work fine without chomp
, but you'll get extra blank lines everywhere.
first_name = gets.chomp
- size
'Ruby'.size => 5
- reverse
'Ruby'.reverse => "ybuR"
- upcase
'Ruby'.upcase => "RUBY"
- downcase
'Ruby'.downcase => "ruby"
- capitalize
'ruby'.capitalize => "Ruby"
- include?
'Ruby'.include? 'R' => true
'Ruby'.include? 'r' => false
- gsub
'Ruvy'.gsub /v/, 'b' => "Ruby"
- split
greeting = 'Hello, How you doing?'
greeting.split ' '
=> ["Hello,", "How", "you", "doing?"]
Requires double quotes.
name = 'Mateo'
"Your name is #{name}"
=> "Your name is Mateo"
if x < y
'x is less than y'
elsif x > y
'x is greater than y'
else
'x is equals y'
end
unless hungry
'Time to write Ruby programs'
else
'Time to eat'
end
n = 1
while n <= 10
puts n
n += 1
end
n = 1
until n > 10
puts n
n += 1
end
for n in 1..10
puts n
end
An iterator is Ruby method that repeately invokes a block of code
i = 10
loop do
i -= 1
puts i
break if i <= 0
end
The next
keyword skips over certain steps in the loop. For instance, if we don't want to print out the even numbers:
i = 10
loop do
i -= 1
next if i % 2 == 0
puts i
break if i <= 0
end
array = [1, 2, 3, 4, 5]
array.each do |e|
puts e
end
10.times do
puts 'Mateo'
end
3.upto(6) do |n|
puts n
end
10.downto(1) do |n|
puts n
end