Skip to content

Instantly share code, notes, and snippets.

@Zhengquan
Created July 29, 2016 00:06
Show Gist options
  • Save Zhengquan/2016e935ffdaf0ba199cc15f25667e4d to your computer and use it in GitHub Desktop.
Save Zhengquan/2016e935ffdaf0ba199cc15f25667e4d to your computer and use it in GitHub Desktop.
code snippet for ruby workshop
# Everything in Ruby is - Object
class People
attr_accessor :name, :gender, :race, :nationality
def initialize(name='', gender='', race='', nationality='')
@name = name
@gender = gender
@race = race
@nationality = nationality
end
end
person = People.new
person.name = "Zhang San"
person.gender = 'Male'
person.race = 'yellow'
person.nationality = 'China'
puts person.inspect
person.class.class.superclass.superclass
# Open For Change
person = People.new
def person.chef
puts "good"
end
class People
def play
puts "FIFA is great!!!"
end
end
person.chef
person.play
#Connect with Messages
class People
def public_method
puts "I am public!"
end
private
def private_method
puts "I am private!"
end
end
person = People.new
person.public_method
person.private_method
person.send(:private_method)
# Module
module Interest
def kickball
puts "i like kicking ball"
end
def read
puts "i like reading books"
end
def dota
puts "i like playing dota"
end
end
class People
include Interest
end
person.read
person.dota
#
#Inheritance
class InterestPeople < People
def dota
puts "i like playing dota"
end
end
person.dota
# Flow Control
word = 'world'
if word
puts "hello #{word}"
end
puts "hello #{word}" if word
$i = 0;
$num = 5;
while @i < num do
puts("Inside the loop i = #@i" )
@i +=1
end
until $i > $num do
puts("Inside the loop i = #$i" )
$i +=1
end
## Two types of block
[1, 2, 3].each do |i|
puts i
end
[1,2,3].each { |i| puts i }
## Yield
def my_method
puts "reached the top"
yield
puts "reached the bottom"
end
my_method do
puts "reached yield"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment