标签:
#!/usr/bin/ruby
class Sample
def hello
puts "Hello Ruby!"
end
end
# 使用上面的类来创建对象
object = Sample. new
object.hello注意:无参数的函数调用可以省略()class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
enda=1 b=2 puts "a: #a" puts "b: #b"打印结果
a: #a b: #b正确的写法
a=1
b=2
puts "a: #{a}"
puts "b: #{b}"打印结果a: 1 b: 2
class Test2
a=1
b=2
def printVar()
puts "a: #{a}"
puts "b: #{b}"
end
end
hellotest = Test2.new
hellotest.printVar()输出test.rb:5:in `printVar‘: undefined local variable or method `a‘ for #<Test2:0x00000002cf2248> (NameError)
from test.rb:10:in `<main>‘正确的写法class Test2
def printVar(a,b)
puts "a: #{a}"
puts "b: #{b}"
end
end
hellotest = Test2.new
hellotest.printVar(1,2)输出a: 1 b: 2
class Test2
def testPass(a,b)
puts "before add : a: #{a} b: #{b}"
addVar(a,b)
puts "after add : a: #{a} b: #{b}"
end
def addVar(a,b)
a += 1
b += 2
end
end
hellotest = Test2.new
hellotest.testPass(1,2)输出before add : a: 1 b: 2 after add : a: 1 b: 2复杂对象是对象引用
class Obj1
def initialize(a)
@a=a
end
def printVal()
puts "a: #@a"
end
def setA(a)
@a=a
end
def getA()
return @a
end
end
class Test2
def testPass()
testobj = Obj1.new("hello")
a = testobj.getA()
puts "before add : a: #{a}"
addVar(testobj)
a = testobj.getA()
puts "after add : a: #{a}"
end
def addVar(obj)
obj.setA(obj.getA() + " world")
end
end
hellotest = Test2.new
hellotest.testPass()输出before add : a: hello after add : a: hello world
class LearnInstanceVar
@a=1
def printVar()
puts "a: #{@a}"
end
end
test1 = LearnInstanceVar.new
test1.printVar输出$ ruby test.rb a:正确的定义
class LearnInstanceVar
def initialize(a)
@a=a
end
def printVar()
puts "a: #{@a}"
end
end
test1 = LearnInstanceVar.new("hello")
test1.printVar输出$ ruby test.rb a: hello类似java中的private,但是更严格,连定义的位置都只能放在特定的方法里面
#!/usr/bin/ruby
class Customer
@@no_of_customers=0
def printCus()
@@no_of_customers += 1
puts "Total number of customers : #{@@no_of_customers}"
end
end
cust1=Customer.new
cust2=Customer.new
cust1.printCus()
cust2.printCus()a = "Ruby" # 定义一个字符串对象 b = "Ruby" # 虽然和a的内容相同,但是他们是不同的对象 a.equal?(b) # false: a和b指向不同的对象 a == b # true: 他们的内容是相同的
(1..10) === 5 # true: 5属于range 1..10 /\d+/ === "123" # true: 字符串匹配这个模式 String === "s" # true: "s" 是一个字符串类的实例 :s === "s" # true
a = 10 b = 20 c = 30可以写成这样
a, b, c = 10, 20, 30于是在java和c中很麻烦的变量交换,在ruby中可以很简单的写成
a, b = b, c这样的代码
a=1
b=2
c=3
a,b=b,c
puts "a: #{a}"
puts "b: #{b}"
puts "c: #{c}"执行结果为$ ruby test.rb a: 2 b: 3 c: 3
foo = 42 defined? foo # => "local-variable" defined? $_ # => "global-variable" defined? bar # => nil(未定义)还可以检测方法是否定义了
defined? method_call # 如果方法已经定义,则为 True
defined? puts # => "method" defined? puts(bar) # => nil(在这里 bar 未定义) defined? unpack # => nil(在这里未定义)
MR_COUNT = 0 # 定义在主 Object 类上的常量 module Foo MR_COUNT = 0 ::MR_COUNT = 1 # 设置全局计数为 1 MR_COUNT = 2 # 设置局部计数为 2 end puts MR_COUNT # 这是全局常量 puts Foo::MR_COUNT # 这是 "Foo" 的局部常量
标签:
原文地址:http://blog.csdn.net/nsrainbow/article/details/49834097