Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

ruby - Rails optional argument

I have a class

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

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 { }).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's as simple as this:

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')

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)

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')

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

Edit

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...