De?ning a Method
Method names should begin with a lowercase letter.
Methods that act as queries are often named with a trailing ?,
Methods that are “dangerous,” or modify the receiver, may be named with a trailing !.
methods that can be assigned to end with an equals sign (=).
def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")
"#{arg1}, #{arg2}, #{arg3}."
end
def my_other_new_method
# Code for the method would go here
end
Variable-Length Argument Lists(*, asterisk ->Array)
def varargs(arg1, *rest)
"Got #{arg1} and #{rest.join(', ')}"
end
varargs("one") "Got one and "
varargs("one", "two") "Got one and two"
varargs "one", "two", "three" "Got one and two, three"
Methods and Blocks
def take_block(p1)
if block_given?
yield(p1)
else
p1
end
end
take_block("no block") "no block"
take_block("no block") {|s| s.sub(/no /, '') } "block"
if the last parameter in a method de?nition is pre?xed with an ampersand(&),any associated block is converted to a Proc object, and that object is assigned to the parameter.
class TaxCalculator
def initialize(name, &block)
@name, @block = name, block
end
def get_tax(amount)
"#@name on #{amount} = #{ @block.call(amount) }"
end
end
tc = 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"
Calling a Method
Method Return values
def meth_three
100.times do |num|
square = num*num
return num, square if square > 1000
end
end
meth_three → [32, 1024]
num, square = meth_three
num → 32
square → 1024
Expanding Arrays in Method Calls
def five(a, b, c, d, e)
"I was passed #{a} #{b} #{c} #{d} #{e}"
end
five(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(*(10..14).to_a) "I was passed 10 11 12 13 14"
Making Blocks More Dynamic
print "(t)imes or (p)lus: "
times = gets
print "number: "
number = Integer(gets)
if times =~ /^t/
calc = lambda {|n| n*number }
else
calc = lambda {|n| n+number }
end
puts((1..10).collect(&calc).join(", "))
produces:
(t)imes or (p)lus: t
number: 2
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Collecting Hash Arguments
class SongList
def create_search(name, params)
# …
end
end
list.create_search('short jazz songs',
:genre => :jazz,
:duration_less_than => 270)
轉載請註明: 轉自船長日誌, 本文鏈接地址: http://www.cslog.cn/Content/learning_ruby_6_methods/zh-hant/