在Ruby中使用不同的参数和默认值初始化Class的最有效方法是什么? [英] What is the most efficient way to initialize a Class in Ruby with different parameters and default values?
本文介绍了在Ruby中使用不同的参数和默认值初始化Class的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个类和一些属性,您可以在初始化期间设置它们或使用其默认值.
I would like to have a class and some attributes which you can either set during initialization or use its default value.
class Fruit
attr_accessor :color, :type
def initialize(color, type)
@color=color ||= 'green'
@type=type ||='pear'
end
end
apple=Fruit.new(red, apple)
推荐答案
解决此问题的典型方法是使用具有默认值的哈希.如果哈希是方法的最后一个参数,则Ruby具有用于传递哈希值的漂亮语法.
The typical way to solve this problem is with a hash that has a default value. Ruby has a nice syntax for passing hash values, if the hash is the last parameter to a method.
class Fruit
attr_accessor :color, :type
def initialize(params = {})
@color = params.fetch(:color, 'green')
@type = params.fetch(:type, 'pear')
end
def to_s
"#{color} #{type}"
end
end
puts(Fruit.new) # prints: green pear
puts(Fruit.new(:color => 'red', :type => 'grape')) # prints: red grape
puts(Fruit.new(:type => 'pomegranate')) # prints: green pomegranate
这里是一个很好的概述: http://deepfall. blogspot.com/2008/08/named-parameters-in-ruby.html
A good overview is here: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html
这篇关于在Ruby中使用不同的参数和默认值初始化Class的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文