Goal: Teaching ruby to newbies
We will build a self-checkout machine used in a supermarket together.
Here is basic ruby syntax useful to this task.
class Item
def initialize()
end
endclass Item
def initialize(name)
end
enditem1 = Item.new()
item2 = Item.new("apple")require "./item" # read file item.rb under the current folder and insert itclass Item
def initialize(name)
@name = name
end
def print()
puts @name
end
end
Item.new("apple").print() #=> "apple"class Item
def initialize()
end
def price(quantity)
10 * quantity # result of the last line returns automatically
end
endprice = Item.new().price(5) #=> 50if (1 == 1)
puts "case1"
elsif (2 == 2)
puts "case2"
else
puts "case3"
endcase 1
when 1
puts "1"
when 2
puts "2"
endname = "apple"name = "apple"
puts name + "orange" #=> apple orangename = "apple"
puts "having #{name}" #=> having applearray = []array = []
array << "mlik"array = ["apple", "orange"]
array[0] #=> "apple"array = ["apple", "orange"]
array.index("apple") #=> 0array = ["apple", "orange"]
array.each do |item|
puts item # execute this line for each item
end #=> "apple\norange"
array.each { |item| puts item } # same as abovearray = [1,2,3]
array.map do |item|
item * 3
end #=> [3,6,9]require 'minitest/autorun'
describe "math" do # 'describe' block wraps 'it' blocks
it "can sum two numbers" do # 'it' block represents single test
assert_equal(2, 1 + 1) # assertion
end
endexpected = true
actual = (1 + 1 == 2)
assert_equal(expected, actual)