So I recently took up Ruby course in Code Academy and I’ll share some of the basic codes of Ruby that I’ve already taken up on Code Academy.
Declaring Variables for different Data Types
my_Name = "Boinx" #String
my_Decision = True #Boolean
my_age = 21 #Integer
Puts and Print
puts "Hi"
puts "Hello!"
print "Boinx"
print "Bantug"
#Output
Hi
Hello!
BoinxBantug
When you use “puts”, it’ll automatically print the next item you’ll print on the next line unlike “print” which prints the next item on the same line.
Methods
"Boinx".length #Will return the length of the string "Boinx"
"Hello".reverse #Will return the reverse of the string "Hello" which is "olleH"
"BOINX".downcase #Will make all the letters in lowercase.
"boinx".upcase #Will make all the letters in uppercase.
"boinx".capitalize #Will make the first letter in uppercase.
Commenting
#using "#" in comment will allow you to put a comment on one line or single line comments
=begin
And this is how to make a multi line comment.
Start it with "=begin"
and close it with "=end"
=end
Getting inputs from users
first_name = gets
last_name = gets.chomp
=begin
"gets" is the method for getting user inputs. I used a variable here to store the users' input, the .chomp method is used
to eliminate the extra blank line produced by Ruby when getting users' input.
=end
Printing variables
first_name = "Boinx"
print #{first_name}
Conditional Statements
user_num = 0;
happy = true
#if,elsif,else
if user_num < 0
puts "Less than zero"
elsif user_num > 0
puts "Greater than zero"
else
puts "Equal to zero"
end
#unless
unless happy
puts "I'm sad!"
else
puts "I'm happy!"
end
Loops
counter = 1
number = 20
#While Loop
while counter < 11
puts counter
counter += 1
end
#Until Loop
until counter == 10
puts counter
counter +=1
end
#For Loop
for number in 1...15 #doesn't include 15 when printed
puts num
end
for number in 1..15 #includes 15 when printed
puts num
end
#Loop method
loop do #prints the number until number == 0
number -=1
print "#{number}"
break if number <=0
end
loop do #prints the number until number == 0 but skips even numbers.
number -=1
next if i%2 == 0
print "#{number}"
break if number <=0
Making an Array
boinxArray = [1,2,3,4,5]
Iterating on Array
boinxArray = [1,2,3,4,5]
boinxArray.each do |a| #You can use any name on your item, here I've used "a"
#enter what you want to do here
end
.times method
20.times{puts "Hello"}
#This will print out 20 "Hello"
That’s it for now will update my blog for part 2. Thanks!