Ruby method 学习笔记
学习笔记,来自于Programming Ruby 1.9
Ruby 关于Method
一、 定义方法
使用关键字 def
方法名称以小写字母或下划线开头,后面跟着字母、数字和下划线
有的方法名后面跟着?,!或=
方法名有?通常意味着方法返回boolean型结果
例:
1.even? # => false2.even? # => true1.instance_of?(Fixnum) # => true
def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")"#{arg1}, #{arg2}, #{arg3}."endcool_dude # => "Miles, Coltrane, Roach."cool_dude("Bart") # => "Bart, Coltrane, Roach."cool_dude("Bart", "Elwood") # => "Bart, Elwood, Roach."cool_dude("Bart", "Elwood", "Linus") # => "Bart, Elwood, Linus."
def varargs(arg1, *rest)"arg1=#{arg1}. rest=#{rest.inspect}"endvarargs("one") # => arg1=one. rest=[]varargs("one", "two") # => arg1=one. rest=[two]varargs "one", "two", "three" # => arg1=one. rest=[two, three]
class Child < Parent def do_something(*not_used) # our processing super endend
class Child < Parent def do_something(*) # our processing super endend
def split_apart(first, *splat, last) puts "First: #{first.inspect}, splat: #{splat.inspect}, " + "last: #{last.inspect}"endsplit_apart(1,2)split_apart(1,2,3)split_apart(1,2,3,4)produces:First: 1, splat: [], last: 2First: 1, splat: [2], last: 3First: 1, splat: [2, 3], last: 4
def double(p1) yield(p1*2)enddouble(3) {|val| "I got #{val}" } # => "I got 6"double("tom") {|val| "Then I got #{val}" } # => "Then I got tomtom"
class TaxCalculator def initialize(name, &block) @name, @block = name, block end def get_tax(amount) "#@name on #{amount} = #{ @block.call(amount) }" endendtc = TaxCalculator.new("Sales tax") {|amt| amt * 0.075 }tc.get_tax(100) # => "Sales tax on 100 = 7.5"tc.get_tax(250) # => "Sales tax on 250 = 18.75"
def meth_one "one"endmeth_one # => "one"def meth_two(arg) case when arg > 0 then "positive" when arg < 0 then "negative" else "zero" endendmeth_two(23) # => "positive"meth_two(0) # => "zero"
def meth_three 100.times do |num| square = num*num return num, square if square > 1000 endendmeth_three # => [32, 1024]num, square = meth_threenum # => 32square # => 1024
def five(a, b, c, d, e) "I was passed #{a} #{b} #{c} #{d} #{e}"endfive(1, 2, 3, 4, 5 ) # => "I was passed 1 2 3 4 5"five(1, 2, 3, *['a', 'b']) # => "I was passed 1 2 3 a b"five(*['a', 'b'], 1, 2, 3) # => "I was passed a b 1 2 3"five(*(10..14)) # => "I was passed 10 11 12 13 14"five(*[1,2], 3, *(4..5)) # => "I was passed 1 2 3 4 5"
class SongList def search(name, params) # ... endendlist.search(:titles, { :genre => "jazz", :duration_less_than => 270 })
list.search(:titles, :genre => 'jazz', :duration_less_than => 270)
list.search(:titles, genre: 'jazz', duration_less_than: 270)