Class TShirt
def size(suggested_size)
if suggested_size == nil
size = "please choose a size"
else
size = suggested_size
end
end
end
tshirt = TShirt.new
tshirt.size("M")
== "M"
tshirt = TShirt.new
tshirt.size(nil)
== "please choose a size"
Run Code Online (Sandbox Code Playgroud)
在方法中使用可选对象的更好方法是什么?特效?
您可能正在寻找默认值:
def size(suggested_size="please choose a size")
Run Code Online (Sandbox Code Playgroud)
您可以在wikibooks上找到有关默认值的更多信息.它们还遍历可变长度参数列表以及向方法传递选项哈希的选项,这两个都可以在很多Rails代码中看到...
文件供应商/ rails/activerecord/lib/active_record/base.rb,第607行:
def find(*args)
options = args.extract_options!
validate_find_options(options)
set_readonly_option!(options)
case args.first
when :first then find_initial(options)
when :last then find_last(options)
when :all then find_every(options)
else find_from_ids(args, options)
end
end
Run Code Online (Sandbox Code Playgroud)
文件供应商/ rails/activerecord/lib/active_record/base.rb,第1361行:
def human_attribute_name(attribute_key_name, options = {})
defaults = self_and_descendants_from_active_record.map do |klass|
"#{klass.name.underscore}.#{attribute_key_name}""#{klass.name.underscore}.#{attribute_key_name}"
end
defaults << options[:default] if options[:default]
defaults.flatten!
defaults << attribute_key_name.humanize
options[:count] ||= 1
I18n.translate(defaults.shift, options.merge(:default => defaults, :scope => [:activerecord, :attributes]))
end
Run Code Online (Sandbox Code Playgroud)
如果您希望在对象中具有可选属性,则可以在类中编写getter和setter方法:
Class TShirt
def size=(new_size)
@size = new_size
end
def size
@size ||= "please choose a size"
end
end
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的TShirt类的实例上调用use tshirt.size ="xl"和tshirt.size.