函数

函数 #

定义函数 #

当函数没有参数时,定义时可以省略 ()

def hello
  return "hello"
end

调用函数

无论函数是否有参数,调用时都可以省略括号,但是如果有参数的话需要与参数之间留出一个空格 add 1,2

puts hello()
puts hello

! 与 ? #

Ruby 中内置的函数通常有两种特别的后缀 !?

! 表示函数会改变参数本身,? 表示函数返回的是布尔值。

str = 'FooBar'
puts str.downcase!
puts str.include? 'foo'

变参 #

Ruby 使用 * 表示变参,变参是被保存在数组中进行传递的

def sum(*n)
  result = 0
  n.each { |i| result += i }
  return result
end

调用变参函数

sum(1, 2, 3)

参数默认值 #

def say(name, word = "hello")
  puts "#{name}, #{word}"
end

say('Peter') # => Peter, hello

返回值 #

Ruby 中使用 return 返回函数的执行结果。除了单一结果外,Ruby 也支持返回多个结果。 如果函数只返回单个结果时可以省略 return 关键字,但是多个结果时则不支持。

返回单个结果

def add(x, y)
  x + y
end

add(1, 2) # => 3

返回多个结果

def triple(x, y, z)
  return x * 3, y * 3, z * 3
end

x, y, z = triple(1, 2, 3) # => x=3, y=6, z=9

命名参数 #

Ruby 中需要通过 Hash 来实现命名参数的功能

def add(a_number, another_number, options = {})
  sum = a_number + another_number
  sum = sum.abs if options[:absolute]
  sum = sum.round(options[:precision]) if options[:round]
  sum
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)

判断函数是否存在 #

puts [1, 2, 3].respond_to?(:push) # true
puts [1, 2, 3].respond_to?(:to_sym) # false

函数与 Symbol #

method() 函数可以通过函数的 Symbol 获得其自身的 Method 对象来进行调用

def add(x, y)
  x + y
end
action = method(:add)
puts action.call(2, 3)
沪ICP备17055033号-2