print "hello world!"
puts "hello world!"
p "hello world!"
# say hello
=begin
this is a long comment
=end
local: time or _time
instance: @time
class: @@time
global $time
Numeric
String
Symbol
Boolean
Array
Hash
"hello #{name}"
a,b = b,a
3.times{ puts "hello"}
"hello" * 3
if(a>5)
puts a
end
if a > 5 then puts a end
puts a if a > 5
puts "miss it" if !name
puts "miss it" unless name
a > 5 ? puts(a) : "oh no"
if name == "jack"
"i am rose"
elsif name == "rose"
"jack i miss u"
else
"get out from here"
end
case name
when "jack" then "i am rose"
when "rose" then "jack i miss u"
else "get out from here"
end
3.times{ puts "hello world" }
for x in [1,2,3]
puts x
end
while i > 5 do
i -= 1
end
i -= 1 while i > 5
until i <= 5 do
i -= 1
end
i -= 1 until i<= 5
loop do
puts "我自豪"
end
break
next
redo
retry
def plus(x,y)
z = x + y
return z
end
plus(3, 4)
def plus x,y
x+y
end
plus 3,4
def hello
yield
end
hello {puts "hello, block"}
def hello &block
block.call
end
hello {puts "hello, block"}
lambda{}
Proc.new{}
Proc中return会跳出当前作用域
lambda中return不会跳出当前作用域
[1,2,3,4,5].each{|i| puts i}
[1,2,3,4,5].each_with_index{|i, index| puts i, index}
[1,2,3,4,5].map{|i| i**2 }
[1,2,3,4,5].select{|i| i%2==0 }
[1,2,3,4,5].reject{|i| i%2==0 }
[1,2,3,4,5].inject{|sum, i| sum += i}
class Bird
attr_accessor :name, :sex
def initialize name
@name = name
end
def self.fly
puts "bird can fly"
end
def say
puts "i am #{@name}"
end
end
bird = Bird.new("didi")
bird.sex = "male"
Bird.fly
class LittleBird < Bird
def initialize name
super(name)
end
end
attr_reader :name
attr_writer :sex
ruby没有interface,只有比interface更强大的module与mixin机制
module Eat
def eat
p "i can eat"
end
end
module Sleep
def sleep
p "i can sleep"
end
end
class Pig
include Eat
include Sleep
end
Pig.new.eat
Pig.new.sleep
module Math
PI = 3.14
end
Math::PI
module Foo
module Bar
def self.say
p "Hi"
end
end
end
Foo::Bar.say
module Foo
class Bar
def say
p "Hi"
end
end
end
Foo::Bar.new.say
module Item
extend self
def name
p "i'm item"
end
end
Item.name
class Fixnum
def plus n
self + n
end
end
1.plus 3
[Fiber](https://gist.github.com/1050566)
[Class](https://gist.github.com/872171)
[System](https://gist.github.com/822091)
[Proc](https://gist.github.com/874438)
/
#