【问题标题】:In Ruby, can I have a Struct within a Struct?在 Ruby 中,我可以在 Struct 中有一个 Struct 吗?
【发布时间】:2015-07-29 20:23:41
【问题描述】:

我想编写如下逻辑结构:

category
  name
  description
  fields

field
  name
  description 

我为此使用了液滴。所以如果我有:

class FieldDrop < liquid::Drop
  def initialize(field)
    @field = field
  end
  def name
    @field.name
  end
  def description
    @field.description
  end
end

那么如何让 CategoryDrop 类在其 def fields 方法中引用 FieldDrop?

我的结构是:

Category = Struct.new(:name, :description, :fields)

基于CategoryDrop

def fields
  @category.fields
end

我希望def fields 扩展为每个字段的@field.name + ' ' + @field.description。

【问题讨论】:

  • “结构中的结构”是什么意思? Ruby 并不完全有结构。
  • @iamnotmaynard 不确定这是 OP 想要的,但 Ruby 确实有结构。 ruby-doc.org/core-2.2.2/Struct.html
  • 啊,我明白了。我以前看过那些,但忘记了。我在考虑 C 风格的结构。
  • 根据您的命名,我想知道:每个类别是否可能有多个Field?那么,您是否正在寻找Struct 中的Struct 列表或集合,而不仅仅是Struct 中的Struct

标签: ruby struct liquid


【解决方案1】:

根据您的问题的命名和描述,听起来您想要在另一个 Struct 中的 Struct 集合或列表,而不仅仅是在 Struct 中的 Struct

定义一个Category 结构:

Struct.new('Category', :name, :description, :fields)
 => Struct::Category

定义一个Field 结构:

Struct.new('Field', :name, :description)
 => Struct::Field

当您创建Category 实例时,它可以有一个fields 成员的数组,该数组最初可能为空:

@category = Struct::Category.new('Foo', 'This is a foo', Array.new)
=> #<struct Struct::Category name="Foo", description="This is a foo", fields=[]>

然后给@category添加一些字段:

@category.fields << [ 'Field 1', "This is field 1" ]
@category.fields << [ 'Field 2', 'This is field 2' ]
...

那么您的字段显示方法可能如下所示:

def fields
  @category.fields.each { |f| puts f.name + ' ' + f.description }
end

或者你想对这些字段做什么。

【讨论】:

  • @user962915 不客气。如果您认为我的回答可以接受,如果您可以检查“接受”复选标记以表示您接受,我将不胜感激。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2012-08-17
相关资源
最近更新 更多