在 ruby​​ 中创建惯用的对象 [英] Idiomatic object creation in ruby

查看:38
本文介绍了在 ruby​​ 中创建惯用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ruby​​ 中,我经常发现自己写了以下内容:

In ruby, I often find myself writing the following:

class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end

甚至

class Foo
  attr_accessor :bar, :baz

  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end

我总是热衷于尽可能地减少样板文件 - 那么在 ruby​​ 中是否有更惯用的方法来创建对象?

I'm always keen to minimise boilerplate as much as possible - so is there a more idiomatic way of creating objects in ruby?

推荐答案

一种选择是你可以从 Struct 继承你的类定义:

One option is that you can inherit your class definition from Struct:

class Foo < Struct.new(:bar, :baz)
  # << more stuff >>
end

f = Foo.new("bar value","baz value")
f.bar #=> "bar value"
f.baz #=> "baz value"

这篇关于在 ruby​​ 中创建惯用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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