方法

方法的定义

def hello(name)
    p "Hello, #{name}"
end

hello "Aaron"

参数的默认值

def hello(name="ruby")
    p "Hello, #{name}"
end

hello "Aaron"

带块的方法

def myloop
    while true
        yield
    end
end

num = 1
myloop do
    p "num is #{num}"
    break if num > 100
    num *= 2
end

参数个数不确定的方法

    def foo *args
        args
    end

    p foo 1, 2, 3
    #[1, 2, 3]

关键字参数

def meth(x: 0, y: 0)
    [x, y]
end

p meth(x:1, y: 2)
#=> [1, 2]

#args = {x: 1, y: 2}
#p meth args

不确定个数的关键字参数

def meth(x: 0, y: 0, **args)
    [x, y, args]
end

p meth(x:1, y: 2, a: 3, b: 4)
#=> [1, 2, {:a=>3, :b=>4}]

把数组分解为参数

def foo(a, b, c)
    a + b + c
end

args1 = [2, 3]
p foo(1, *args1)

args2 = [1, 2, 3]
p foo *args2

把hash作为参数传递

def foo arg
    arg
end

p foo {"a"=>1, "b"=>2}
p foo "a"=>1,"b"=>2
p foo a: 1, b: 2