ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Ruby -- 小结1

Ruby -- 小结1

原创 Linux操作系统 作者:littlebig 时间:2010-12-12 17:56:58 0 删除 编辑
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) # #
p(c.get_self()) # #

通过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"

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/694085/viewspace-681584/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2010-12-12

  • 博文量
    2
  • 访问量
    1665