Ruby -- 小结1

上一篇 / 下一篇  2010-12-12 16:40:09 / 个人分类:Ruby

A.对于Ruby来说任何可操作的东西都是对象,里面有:
1.string:“hello world!”
2.字面量(literal):123,1.4e4,1.0,99.40
3.数组:
[1, 2, 3],[1, "string", 2, ["nested", "array"]]
4.hash表:{"key"=>"value", "key2"=>"value2", "key3"=>"value3"}

B.方法调用:
"hello world!".upcase(),"hello world!".upcase().downcase();
例子:
p("helloworld")
p("helloworld".upcase())
p("helloworld".downcase())
对于常量的,一般是以大些字母开头的,重新给常量赋值,会得到警告信息:
Const="hello world"
p(Const)
Const=3.4
p(Const)
运行上面例子,会得到一个警告信息,但不是错误

C.类
Class C
  def myupcase( str )
    return str.upcase()
  end
end
p(C.new().myupcase("content"))

Self:
class C
def get_self()
return self
end
end

c = C.new()
p(c) # #<C:0x40274e44>
p(c.get_self()) # #<C:0x40274e44>

通过self 调用方法:
class C
def my_p( obj )
self.real_my_p(obj) # 通过自身调用方法
end

def real_my_p( obj )
p(obj)
end
end

C.new().my_p(1) # 显示1
省略self的调用:
class C
def my_p( obj )
real_my_p(obj) # 可以不指定调用的接收者
end

def real_my_p( obj )
p(obj)
end
end

C.new().my_p(1) # 显示1
初始化类(initialize)
class C
  def initialize()
    @i = "ok"
  end
  def get_i()
    return @i
  end
end
c = C.new()
p(c.get_i())   # 显示"ok"

继承
class C
def hello()
return "hello"
end
end

class Sub < C
end

sub = Sub.new()
p(sub.hello()) # 显示"hello"
Override:
class C
def hello()
return "Hello"
end
end

class Sub < C
def hello()
return "Hello from Sub"
end
end

p(Sub.new().hello()) # 显示"Hello from Sub"
p(C.new().hello()) # 显示"Hello"





TAG:

 

评分:0

我来说两句

Open Toolbar