03/13/2017
RubyMonk Primer Notes

RubyMonk Tutorial

6.2 Calling a method

  • 传入method的参数可以是不固定的. 比如:
1
2
3
4
5
6
7
8
def add(*numbers)
# 0 is the start number
numbers.inject(0) { |sum, num| sum + num }
end
def add_with_message(message, *numbers)
"#{message} : #{add(*numbers)}"
end

注意ruby method规定如果没有return statement的话,最后一行就是return的东西.

  • ruby 允许method的最后一个参数是一个hash, 然后在传参数的时候,只要指定任意数量的key: val pairs即可, 不用担心参数的数量不对. 举个栗子:
1
2
3
4
5
6
7
8
9
def add(num1, num2, options = {})
sum = num1 + num2
sum = sum.abs if options[:absolute]
sum = sum.round(options[:precision]) if options[:round]
end
puts add(1.0134, -5.568)
puts add(1.0134, -5.568, absolute: true)
puts add(1.0134, -5.568, absolute: true, round: true, precision: 2)

注意必须要指定options为Hash.
实际上三次add() 都是只有3个参数: two numbers and a Hash

Read More

© 2019 ReeeStart with help from Hexo and Twitter Bootstrap. Theme by Freemind.