#定义方法
def method
puts 'method'
end
#调用时可以带或不带()均可
method #method
method() #method
#使用参数
def methodUseArgs(arg1,arg2)
print arg1,arg2
end
#调用时可以带或不带()均可
methodUseArgs('hello',"World\n")#helloWorld
methodUseArgs 'hello',"World\n" #helloWorld
#使用默认参数
def methodUseDefaultArgs(arg1,arg2="World\n")
print arg1,arg2
end
methodUseDefaultArgs("Hello")#HelloWorld
#使用可变长度的参数
def methodUseVariableLenthArgs(*args)
puts "#{args.join(' ')}"
end
methodUseVariableLenthArgs('hello','world ')#hello world
#使用块block
def methodUseBlock(arg)
if block_given?
yield arg
else
arg
end
end
puts methodUseBlock("no block")#no block
puts methodUseBlock("no block"){|arg| arg.sub('no','')}# block
#使用&将块转为proc对象
class SampClass
def SampClass.methodConvertBlock2Proc(&proc)
@@proc=proc
end
def SampClass.executeProc(amount)
puts "pi*#{amount}->#{@@proc.call(amount)}"
end
end
SampClass.methodConvertBlock2Proc{|amount| result=amount*Math::PI}
SampClass.executeProc(5) #pi*5->15.707963267949
SampClass.executeProc(20) #pi*20->62.8318530717959
#ruby中的方法有个有趣的地方是可以返回多个值
def methodReturn2Variable
return '3Q','ruby'
end
result1,result2=methodReturn2Variable
puts result1,result2 #3Q ruby
#调用时护展数组
def method3args(arg1,arg2,arg3)
print arg1,arg2,arg3,"\n"
end
method3args(1,2,3) #123
method3args(*[1,2,3]) #123
method3args 1,*[2,3] #123
method3args *(1..3).to_a #123
#更一般更灵活的是使用lambda将一个块转换为一个proc对象
proc1=lambda{|n| n*=2}
puts proc1.class #proc
#下面的两种写法是等价的
puts (1..10).collect{|n| n*=2}.join(' ')#2 4 6 8 10 12 14 16 18 20
puts (1..10).collect(&proc1).join(' ')#2 4 6 8 10 12 14 16 18 20
#使用哈希表
def methosUseHash(hashtable)
hashtable.collect{|de| print "key:#{de[0]} value:#{de[1]}\n"}
end
methosUseHash({"key"=>"k","value"=>"v"})#key:value value:v key:key value:k
#可以省略{}
methosUseHash("key"=>"k","value"=>"v") #同上
#更进一步可以省略""号
methosUseHash(:key=>:k,:value=>:v) #同上
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/blackant2/archive/2006/12/03/1427582.aspx
ruby学习笔记(7)-方法
最新推荐文章于 2024-10-07 21:15:56 发布