参数的六种方式
#一般模式,括号可以省略,但是参数名不能为常量,即one.不能写为One
def demo(one, two) #这里的括号可以省略,下面调用的括号也可以省略括号
puts one
puts two
end
demo("hello", "world")
#命名参数
def demo one:, two:
puts one
puts two
end
demo(one: "hello", two: "world") #参数调用的时候可以改变参数的调用顺序
#默认参数
def demo one:, two: "world"
puts one
puts two
end
demo(one: "hello") #默认参数
demo(one: "hello", two: "animal") #覆盖默认参数
#单个星号参数,表示这边需要输入多个参数,返回的是数组
def demo *argument
p argumen
end
demo "one", "two", "three" #["one", "two", "three"], 返回的是数组
#两个星号的参数,输入的参数值必须是hash
def demo **argument
argument.each do |name, index|
puts "name: #{name}"
puts "index: #{index}"
puts "\n"
end
end
data = {
"jayzen": "18",
"jay": "28"
}
demo data
#更常见的hash参数形式
def invoice options={}
puts options[:company]
puts options[:total]
end
invoice company: "Google", total: "1"
参数的顺序
必要参数>可变参数>命名参数
对于已经赋值的命名参数,可以直接调用方法而不用使用参数
#直接调用方法而不使用参数
def demo hello: "hello world"
hello
end
demo # "hello world"
#覆盖参数值可以带上参数和值
def demo hello: "hello world"
hello
end
demo(hello: "ni hao") # "ni hao"