27
loading...
This website collects cookies to deliver better user experience
3.0.2
on July 7th but it is beyond the current scope of this article."... Knowledge does not occupy space!"
"... necessity for software to be understood by humans first (🙋🥇) and computers second (🗣️ losers!)."
" ... It was was created by Yukihiro Matsumoto (Matz), in Japan."
" ... with the idea that programming should be fun for programmers."
gif
below is in your honor! 🤜🤛irb
console and an IDE
in the same page.IRB stands for "interactive Ruby" and is a tool to interactively execute Ruby expressions ...
Module: IRB
=begin
and =end
keywords and placing the block to be comment between them.=begin
Dale a tu cuerpo alegria Macarena
Eeeh Macarena ....
Aaahe!
=end
#
.# Never gonna give you up, never gonna let you down ...
puts
inserts a newline at the end.print "Hello, "
print "darkness my old friend."
# Result:
# Hello, darkness my old friend
puts "Hark, hark! I hear"
puts "The strain of strutting chanticleer"
puts "Cry, Cock-a-diddle-dow!"
# Result:
=begin
Hark, hark! I hear
The strain of strutting chanticleer
Cry, Cock-a-diddle-dow!
=end
variables
where which one is declared in its specific way:local = "Hey, I am a local variable."
_other_local_var = "Never mess up with a local!"
@instance = "For instance, I am an instance variable."
@@class = "I am 'classy'."
$global = "Globalization rules!"
String
, Integer
, Float
, Boolean
(TrueClass
, FalseClass
), Symbol
and Nil
(NilClass
). $my_name = "Clancy Gilroy"
puts $my_name.class # String
name = "X Æ A-12"
puts name.class # String
age = 35
puts age.class # Integer
gpa = 3.22
puts gpa.class # Float
had_fun = true
puts had_fun.class # TrueClass
is_hot = false
puts is_hot.class # FalseClass
week_points = nil
puts week_points.class # NilClass (absence of value)
symbol = :hello
puts symbol.class # Symbol
.class
method ? Since Ruby is a Fully Object Oriented language everything is an object
, a property of
or a method call on
an object.class
like a blueprint for creating objects, which determines initial values, attributes, behavior etc..superclass
method.puts TrueClass.superclass # Object
puts Integer.superclass # Object
puts String.superclass # Object
puts Object.superclass # BasicObject
# so on and so forth
phrase = " Sometimes I’m confused by what I think is really obvious. But what I think is really obvious obviously isn’t obvious. "
puts phrase.upcase
puts phrase.downcase
# hint: .strip removes the empty spaces from both beginning and ending.
puts phrase.strip
puts phrase.length
puts phrase.include? "Some"
puts phrase.include? "Sure"
puts phrase.index("confused")
puts "auckland".capitalize
strings
.character_age = "17"
character_name = "Link"
# Interpolation
puts "There once was a young man named #{character_name}"
# Concatenation ➕
# '.to_s' is the short method name for 'to string'
# There is more like '.to_i', '.to_f', '.to_a' etc
puts "he was " + character_age.to_s + " years old"
puts 5 + 9 # addition
puts 2 - 9 # subtraction
puts 6 * 9 # multiplication
puts 10 / 7.0 # division
puts 2 ** 3 # exponentiation
puts 3 % 2 # modulo or remainder
num = -163.23
num2 = 45.47
# returns the absolute number
puts num.abs # 163.23
# return a value rounded to the nearest value with "n" digits decimal digits precision.
puts num2.round # 45
# returns the ceil value
puts num2.ceil # 46
# returns the floor value
puts num2.floor # 45
# returns the square root of a given number (5.0)
puts Math.sqrt(25) # 5.0
# returns the natural logarithm (base e) or logarithm to the specified base of a given number, e.g. Math.log(x, base).
puts Math.log(100) # 4.605170185988092
# different ways to declare an array
friends = Array["Rapha", "Alexandre", "Andre", "Bogus"]
# I prefer this one 👇
fruits_array = ["cherimoya", "durian", "lamut", "langsat" ]
# What the heck? 🤢
hello = Array.new(5, "awful").to_s
# output: ["awful", "awful", "awful", "awful", "awful"]
puts hello
# Remind: Ruby Arrays indexing starts at 0.
puts friends[0] # Rapha
puts friends[-1] # Bogus
puts friends[0,2] # Rapha Alexandre
# Replacing items
friends[0] = "Fael"
# output: ["Fael", "Alexandre", "Andre", "Bogus"]
puts friends.to_s
puts friends.length # 4
# Down here the methods syntax are pretty much understandable
puts friends.include?("Fael")
puts friends.reverse
puts friends.sort
puts friends.empty?
puts fruits_array.push("rambutan")
## the example above (`push`) could also be done as shown below
fruits_array << "akebi"
random_hash = {
:sao_paulo => "SP",
"rio_de_janeiro" => "RJ",
1 => "NY",
}
key
is the same you will use in order to successfully access its value
in a hash.random_hash["sao_paulo"]
would return nothing because :sao_paulo
is not the same as "sao_paulo"
. (Symbol
x String
)puts random_hash
puts random_hash[:sao_paulo] # SP
puts random_hash["rio_de_janeiro"] # RJ
puts random_hash[1] # NY
puts random_hash.nil? # false
puts random_hash.length # 3
length
, sqrt
, to_s
etc. "... If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. "
Source: Tutorials Point
# Method without parameter(s)
# This is how you declare a method
def say_konnichiwa
puts "こんにちは"
end
# This is how you invoke it
say_konnichiwa
# Method with parameter(s)
def say_tadaima(title, name="Unknown")
puts "ただいま, #{title} #{name}!"
end
say_tadaima("Mr.", "Toguro") # prints "ただいま, Mr. Toguro!"
name
holds the default value Unknown
. In other words, if we call the same method without providing the second argument, the default value will be put in place. Example below:say_tadaima("Mr.") # prints "ただいま, Mr. Unknown!"
return
values from inside of our methods both explicitly or implicitly.return
:def cube(num)
return num * num * num, 70, "return", true, "?????"
# Never reached
puts "No value after the return statement is reached"
end
# IT will console the result of "num * num * num"
puts cube(3)
# Prints the number "70"
puts cube(3)[1]
# Prints the string "return" and so on
puts cube(3)[2]
return
:def always_return
"I am always returned"
end
# Variable created for the sake of demonstration
result = always_return
puts result # "I am always returned"
is_dev = true
language = "Cobol"
if(is_dev && language == "Cobol")
puts "DISPLAY 'Hello, Cobol'."
elsif (is_dev && language == "Pascal")
puts "writeln('Hello, Pascal!');"
elsif (is_dev && language == "Delphi")
puts "ShowMessage('Hello Delphi');"
else
puts "👋"
end
if / else
statements.def max_number(num1, num2, num3)
if (num1 >= num2 and num1 >= num3)
return num1
elsif (num2 >= num1 and num2 >= num3)
return num2
else
return num3
end
end
puts max_number(9, 53, 77)
def get_day_name(day_abbreviaton)
day_name = ""
case day_abbreviaton.downcase
when "ma"
day_name = "Maanantai"
when "ti"
day_name = "Tiistai"
when "ke"
day_name = "Keskiviikko"
when "to"
day_name = "Torstai"
when "pe"
day_name = "Perjantai"
when "la"
day_name = "Lauantai"
when "sun"
day_name = "Sunnuntai"
else
day_name = "En tiedä!"
end
# Implicit returns the value
day_name
end
puts get_day_name("ma") # Maanantai
puts get_day_name("koira") # En tiedä!
lucky_num = 70
# Note that the 'not' keyword is similar to '!=' (negation)
while not lucky_num == 77
puts "No Lucky #{lucky_num}"
lucky_num +=1
end
# You already know what is an array :)
people = ["C. Falcon", "Fox", "DK", "Ness", "Samus"]
# It will display all names in a different line
for person in people
puts person
end
# Same same but ... same
people.each do |person|
puts person
end
# Display numbers from range 0 to 5 (inclusive ..)
for inclusive in 0..5
puts inclusive
end
# Display number from range 0 to 4 (exclusive ...)
for exclusive in 0...5
puts exclusive
end
# Let's agree: This is plain English
# PS.: counting starts from 0
6.times do |phrase|
puts "Counting: #{phrase}"
end
Java
. ## This is a very simple class
class Character
attr_accessor :name, :role, :home
end
## This is a very simple way to create a new object
character = Character.new()
character.name = "Rygar"
character.role = "Searcher"
character.home = "Black Mountains"
puts character.name
attr_...
creates the so famous getters
and setters
for you, for instance:attr_accessor
: creates the getter
and setter
methods.attr_reader
: creates only the getter
method.attr_writer
: creates only the setter
method.# In other words this
attr_acessor :name
# Is the equivalent of
def name
@name
end
def name=(value)
@name = value
end
# Note: The equals sign is a Ruby convention when creating setters.
# Omitting it is considering a bad practice but still works.
# (if it is working don't touch! 👍)
class
in Ruby.class Shoes
attr_accessor :brand, :size, :color
# Allows you to set the initial values for a given object
# Does 'constructor' sound familiar to you?
def initialize(brand, size, color)
@brand = brand
@size = size
@color = color
end
end
trainers = Shoes.new("Kichute", 47, "Heliotrope")
puts trainers.brand # Kichute
class Hero
attr_accessor :name, :animal, :hp
def initialize(name, animal, hp)
@name = name
@animal = animal
@hp = hp
end
# It is a instance method (Good catch, Juan! 🏆)
def has_enough_hp
@hp > 5.5 ? "Able to play" : "Consider resting, #{@name}"
end
end
hero1 = Hero.new("Nakoruru", "eagle", 80)
hero2 = Hero.new("Galford", "husky", 2.9)
# Here we have invoked the object(s) method
puts hero1.has_enough_hp # Able to play
puts hero2.has_enough_hp # Consider resting, Galford
class Fighter
def make_special_attack
puts "Hadouken"
end
def make_uppercut_punch
puts "Makes the uppercut move"
end
end
ryu = Fighter.new()
ryu.make_special_attack # Hadouken
ryu.make_uppercut_punch # Makes the uppercut move
# Subclass - "<" means inherits from
class SpecialFighter < Fighter
# Overwrites 'make_special_attack' method
def make_special_attack
puts "Shun Goku Satsu"
end
# Creates a new method for this class
def celebrate
puts "Is that all? You must be joking!"
end
end
gouki = SpecialFighter.new()
gouki.make_special_attack # Shun Goku Satsu
gouki.make_uppercut_punch # Makes the uppercut move
gouki.celebrate # Is that all? You must be joking!
make_uppercut_punch
move is used by both characters there is no need to re-declare it in our subclass
.module Greeting
def say_hello(name="there")
puts "Hi #{name}."
end
def say_bye_bye(name="dear")
puts "Bye bye #{name}."
end
end
require_relative "./folder/the_name_of_your_file.rb"
include Greeting
Greeting.say_hello("Bowser") # Hi Bowser.
begin
# we have never defined the 'fav_character' variable
# so it will fire the second 'rescue' block
# and will display the customized message even
# knowing that we also tried to make a division by 0
# => Reference to control flow for more <=
fav_character["Makoto Mizuhara"]
num = 45 / 0
rescue ZeroDivisionError => e
puts e
puts "Division By Zero Error"
rescue NameError
puts "undefined local variable or method 'fav_character'."
end
error handling
in action, replace the statement fav_character["Makoto Mizuhara"]
for that one fav_character = ["Makoto Mizuhara"]
. 😉" The curiosity killed the cat."
self.describing
language. (Pun intended 🤦)