ruby.new

ruby.new

输出:print、puts、p

注释

#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

方法

def plus(x,y)
	z = x + y
	return z
end
plus(3,4)
def plus x,y
	x + y
end
plus 3,4
  • 只有overriding没有overloading

block

def hello
        yield
end
hello {puts "hello, block"}
[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}

lambda 和 Proc

class

class Bird
  attr_accessor :name, :sex
  attr_reader :age
  attr_writer :hometown
  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

module

  • ruby 没有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

code

r1.rb

posted @ 2015-12-21 00:04  shang1jk  阅读(244)  评论(0编辑  收藏  举报