Variable, Assignment,
and Condition
Variable and Assignment
Variable and Assignment
Programming is all about creating abstractions, and in order to create an abstraction we must be able to assign names to things. Variables are a way of creating a name for a piece of data.
Variable and Assignment
# Creating a variables and assign their values in Ruby
age = 30
name = "Iqbal Farabi"
is_male = true
Variables in Ruby
1. No declaration needed
# Ruby
age = 30
# C and Java
int age;
age = 30;
# or
int age = 30;
Variables in Ruby
2. Right Side First
width = 10
height = 15
# Ruby evaluates expression in the right side of operator "=" first
# then it names the result with variable in the left side of operator "="
area = width * height
Variables in Ruby
3. Flexible Data Type
# Ruby
a = 10
a = "Hello, World!"
# C and Java
int a;
a = 10;
a = "Hello, World!"; # this expression will cause an error in C and Java
Naming Variables
Must do:
- Begins with lower case
- Contains no space
- Contains no special characters like $, @ and &
Naming Variables
Convention:
- Using snake_case instead of camelCase
- Named after the meaning of its content
- Not abbreviated
Flow Control
Conditional Statements
'if', 'else', and 'elsif'
# Conditional statement with 'if', 'else', dan 'elsif'
require 'date'
if Date.today < Date.new(2017, 9, 18)
puts "Today's date is less than September 18th 2017"
elsif Date.today == Date.new(2017, 9, 18)
puts "Today's date is September 18th 2017"
else
puts "Today's date is greater than September 18th 2017"
end
# Conditional statement with 'if' can also be written inline
puts "Today's date is September 18th 2017" if Date.today == Date.new(2017, 9, 18)
Conditional statement with 'unless'
# Conditional statement with 'unless' and 'else'
require 'date'
unless Date.today.saturday? || Date.today.sunday?
puts "Work hard"
else
puts "Play hard"
end
# Conditional statement with 'unless' can also be written inline
puts "Not freaky" unless Date.today.friday?
Conditional statement with 'case'
# Conditional statement with 'case' and 'when'
require 'date'
case Date.today.strftime("%A")
when "Monday"
puts "Blue"
when "Tuesday"
puts "Grey"
when "Wednesday"
puts "Too"
when "Thursday"
puts "I don't care about you"
when "Friday"
puts "I'm in love"
end
Ternary Operator
# Conditional statement with ternary operator
Time.now.hour < 12 ? "AM" : "PM"
# Ternary operator can also be used to do inline conditional assignment
meridian = Time.now.hour < 12 ? "AM" : "PM"
puts meridian
# In some cases, ternary operator comes in handy
allowed_license_number = Time.now.day % 2 == 0 ? "even" : "odd"
puts "Only cars with #{allowed_license_number} license plate are allowed today"
Boolean Data Type
Boolean
Boolean is a data type that only has two possible values: 'true' or 'false'.
Boolean Operator
a = 1
b = 2
a == b
# false
a > b
# false
a < b
# true
a >= b
# false
a <= b
# true
a != b
# true
Boolean Operator (1)
# Operator &&
# What are the results of these:
true && true
true && false
false && true
true && true
false && false
# Operator ||
# What are the results of these:
true || true
true || false
false || true
true || true
false || false
Boolean Operator (2)
# Operator &&
# What are the results of these:
true && true
# true
true && false
# false
false && true
# false
true && true
# true
false && false
# false
# Operator ||
# What are the results of these:
true || true
# true
true || false
# true
false || true
# true
true || true
# true
false || false
# false
Spaceship Operator
# Spaceship Operator (also called compariosn operator) has special characteristic
# as it has three possible values as folow:
1 <=> 2
# -1
1 <=> 1
# 0
2 <=> 1
# 1
# There's one more value thoug
# if two non comparable things are compared,
# it will return nil
1 <=> 'a'
# nil
Truthy dan Falsey
In some programming languages, we can evaluate non-boolean values in boolean context. To do this, these programming languages implement a concept known as 'truthy' and 'falsey'.
Truthy: non-boolean values that are evaluated as true
Falsey: non-boolean values that are evaluated as false
Truthy dan Falsey
# Truthy and falsey in Ruby
# Only false and nils that are evaluated as falsey
if false
puts "nil is truthy"
else
puts "nil is falsey"
end
if nil
puts "nil is truthy"
else
puts "nil is falsey"
end
# Everything else is evaluated as truthy
[true, false, Object, 0, 1, nil, true, false, "", [1, 2, 3], {}].each do |value|
if value
puts "#{value.inspect} is truthy"
else
puts "#{value.inspect} is falsey"
end
end
Truthy dan Falsey
The implementation of truthy and falsey varies in every programming languages. In Javascript, for instance, 0 and "" are evaluated as falsey. Meanwhile in Python, [] and {} are evaluated as falsey.
Therefore, when we develop a Ruby app that interact with other apps, we need to be aware of the implementation of truthy and falsey in programming languages used in apps that we interact with.
Lazy Evaluation
Ruby evaluates a boolean expression lazily. It means:
1. Ruby does not necessarily evaluate the whole expression, it only evaluates part of expression as far as needed to return a value
2. Ruby will return the last evaluated part of an expression without finish evaluating the whole expression
Lazy evaluation is also known as short circuit evaluation.
Lazy Evaluation
# Lazy Evaluation
# Which message printed by expression below?
puts("Ini pesan yang tidak penting") && puts("INI PESAN YANG PENTING")
# What is the value of c?
a = 1
b = 2
c = a || b
Exercises (1)
# Complete the following skeleton
def fav_programming_language
puts "What is your favorite programming language?"
language = gets.chomp
# your code here
# ......
end
1. Favorite Programming Language
Write a method that prompt a user asking his/her favorite programming language. If user inputs with one of "Ruby", "Python", and "Perl", program will answer with the name of its founder. For instance, "Ruby is created by Yukihiro Matsumoto". If user input other programming languages, program will answer with, "Sorry, I don't know that programming language"
Exercises (2)
how_many_times(40,15)
# will return 3
how_many_times(30,10)
# will return 3
how_many_times(80,15)
# will return 6
2. How Many Times Should I Go?
Djakarta XXI offers you a monthly subscription program. For a certain amount of monthly fee, you can watch movies as many times as you like. Write a method that receives two parameters "monthly_fee" and "individual_ticket", and return the minimum number of times you should go to movie theatre to make your subscription worth it. Build this method without using loop.
Exercises (3)
reverse_words("Hey fellow scholars") # returns "Hey wollef sralohcs"
reverse_words("This is a test") # returns "This is a test"
reverse_words("This is another test") # returns "This is rehtona test"
# Since we have not learned about basic data types and loop in Ruby
# you can follow this skeleton
def reverse_words(sentence)
words = []
sentence.split(" ").each do |word|
# your code here
# clue:
# 1. You can find the number of characters in a word using ".length" or ".size"
# 2. You can reverse a string by using ".reverse"
# 3. You can add element to an array using "<<"
end
words.join(" ")
end
3. Reverse Words
Write a method that receives a sentence (String) and returns the same sentence but with reversed words for words that has five or more characters
Exercises (4-1)
4. Mix Fruit
Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra special fruits cost $9 per each. There is no limit on how many fruits she/he picks.The price of a cup of juice is the mean of price of chosen fruits. In case of decimal number (ex. $5.99), output should be the nearest integer (use the standard rounding function of your language of choice).
Exercises (4-2)
mix_fruit(["banana","mango","avocado"]) # will resturn: 6
mix_fruit(["melon","Mango","kiwi"]) # will resturn: 8
mix_fruit(["watermelon","cherry","avocado"]) # will resturn: 8
mix_fruit(["watermelon","lime","tomato"]) # will resturn: 9
mix_fruit(["blackBerry","coconut","avocado"]) # will resturn: 8
mix_fruit(["waterMelon","mango"]) # will resturn: 8
mix_fruit(["watermelon","pEach"]) # will resturn: 9
mix_fruit(["watermelon","Orange","grapes"]) # will resturn: 6
mix_fruit(["watermelon"]) # will resturn: 9
mix_fruit(["BlACKbeRrY","cOcONuT","avoCaDo"]) # will resturn: 8
def mix_fruit(fruits)
price = 0
fruits.each do |fruit|
# your code here
end
# your code here
# clue: use ".size" method to get the size of an array
end
Insinyur Online - Belajar Ruby - Bagian 2: Variables, Conditionals, dan Boolean Logic
By qblfrb
Insinyur Online - Belajar Ruby - Bagian 2: Variables, Conditionals, dan Boolean Logic
- 189