Rails 可选参数 [英] Rails optional argument

查看:38
本文介绍了Rails 可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有课

class Person
    attr_accessor :name,:age
    def initialize(name,age)
        @name = name
        @age = age
    end
end

我想将年龄设为可选,因此如果未通过则为 0,如果未通过则名称为空

I'd like to make the age optional so its 0 if its not passed, or the name to be blank if not passed

我对此进行了一些研究,但对我发现的内容有些困惑(必须在另一个变量 { } 中传递变量).

Ive researched a bit on it but its a bit confusing as to what i've found (having to pass variables in another variable { }).

推荐答案

就这么简单:

class Person
    attr_accessor :name, :age

    def initialize(name = '', age = 0)
        self.name = name
        self.age = age
    end
end


Person.new('Ivan', 20)
Person.new('Ivan')

但是,如果您只想传递年龄,则调用看起来会很丑陋,因为无论如何您都必须为 name 提供空白字符串:

However, if you want to pass only age, the call would look pretty ugly, because you have to supply blank string for name anyway:

Person.new('', 20)

为了避免这种情况,Ruby 世界中有一个惯用的方法:options 参数.

To avoid this, there's an idiomatic way in Ruby world: options parameter.

class Person
    attr_accessor :name, :age

    def initialize(options = {})
        self.name = options[:name] || ''
        self.age = options[:age] || 0
    end
end

Person.new(name: 'Ivan', age: 20)
Person.new(age: 20)
Person.new(name: 'Ivan')

你可以先把一些必须的参数放进去,把可选的都塞进options.

You can put some required parameters first, and shove all the optional ones into options.

看来 Ruby 2.0 将支持真正的命名参数.

It seems that Ruby 2.0 will support real named arguments.

def example(foo: 0, bar: 1, grill: "pork chops")
  puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
end

# Note that -foo is omitted and -grill precedes -bar
example(grill: "lamb kebab", bar: 3.14)

这篇关于Rails 可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆