Ruby 如何为具有默认值的新对象创建setter方法?

Ruby 如何为具有默认值的新对象创建setter方法?,ruby,setter,Ruby,Setter,在我的测试文件中,我有: def default_product() Product.new(title: "default title", description: "default description", price: 1, image_url: 'default_url.png') end 并希望将其转换为一种方法,可以在不使用args的情况下调用,在这种情况下,将设置默认attr

在我的测试文件中,我有:

def default_product()
  Product.new(title: "default title",
              description: "default description",
              price:       1,
              image_url:   'default_url.png')
end
并希望将其转换为一种方法,可以在不使用args的情况下调用,在这种情况下,将设置默认attrs,或者使用args调用,例如:

default_product(price: 100)
在这种情况下,默认价格将被参数覆盖


实现这一点的正确方法是什么?

使用默认关键字参数:

def default_product(
    title: "default title",
    description: "default description",
    price: 1,
    image_url: 'default_url.png')
  Product.new(
    title: title,
    description: description,
    price: price,
    image_url: image_url)
end
可以这样称呼它:
default\u产品(标题:“另一个标题”)



旁注:正确的方法可能是使用。

使用默认关键字参数:

def default_product(
    title: "default title",
    description: "default description",
    price: 1,
    image_url: 'default_url.png')
  Product.new(
    title: title,
    description: description,
    price: price,
    image_url: image_url)
end
可以这样称呼它:
default\u产品(标题:“另一个标题”)



旁注:正确的方法可能是使用。

你不想使用的原因是什么?一点也不,只是因为我直到现在才意识到这一点。作为一个新手,我试图让事情尽可能简单。我要试试。它绝对是做这项工作的工具。祝你好运。你有什么不想用的理由吗?一点也没有,只是因为我直到现在才意识到这一点。作为一个新手,我试图让事情尽可能简单。我要试试。它绝对是做这项工作的工具。祝你好运。这很好用,可以看看FactoryBot。这很好用,可以看看FactoryBot。