如何使用ruby的输入定义方法的输出格式

如何使用ruby的输入定义方法的输出格式,ruby,methods,eval,Ruby,Methods,Eval,我有以下方法: def response_array_to_list(response_array, line_item) output_line = '' response_array.each_with_index do | item, index | output_line = output_line + line_item + "\n" end return output_line end line\u项用于定义输出行的格式和内容 例如

我有以下方法:

def response_array_to_list(response_array, line_item)

    output_line = ''

    response_array.each_with_index do | item, index |
      output_line = output_line + line_item + "\n"
    end

    return output_line
end
line\u项
用于定义
输出行
的格式和内容

例如,我想在{item['value']['time\u string'].

我显然不能,因为
索引
仅在方法的范围内。但这就是想法

It使用情况应如下所示:

response_array_to_list(response_array, `#{index} - #{item['value']['keyword']) at #{item['value']['time_string']`

=> 1 - keyword here at 10AM
   2 - keyword there at 12PM
response_array_to_list(response_array) { |item, index|
  "#{index} - #{item['value']['keyword']} at #{item['value']['time_string']}"
}

问题:当输入到方法中时,我如何传递一些不试图替换变量的内容,而是按照方法中的意图来解释它。

块。您已经在使用它们了(作为方法调用方,例如
每个带有索引的\u do…end
),现在是从另一端使用它们的时候了(作为方法创建者)。块是不会立即计算的代码片段,对吗

您的“用法”应如下所示:

response_array_to_list(response_array, `#{index} - #{item['value']['keyword']) at #{item['value']['time_string']`

=> 1 - keyword here at 10AM
   2 - keyword there at 12PM
response_array_to_list(response_array) { |item, index|
  "#{index} - #{item['value']['keyword']} at #{item['value']['time_string']}"
}
你的方法是:

def response_array_to_list(response_array)

    output_line = ''

    response_array.each_with_index do | item, index |
      line_item = yield item, index
      output_line = output_line + line_item + "\n"
    end

    return output_line
end
或者,等效地,此优化版本:

def response_array_to_list(response_array)    
    response_array.each_with_index.map { |item, index|
      yield item, index
    }.join("\n") + "\n"
end
编辑如果您需要动态模板(即非硬编码),您可以使用注释中提到的液体进行安全处理:

require 'liquid'
def response_array_to_list(response_array, template)
  compiledTemplate = Liquid::Template.parse(template)
  response_array.each_with_index.map { |item, index|
    compiledTemplate.render 'index' => index, 'item' => item
  }
end

response_array_to_list(response_array, "{{index}} - {{item['value']['keyword']}} at {{item['value']['time_string']}}")

我在这里找到了其他人的帖子:

解决方案是使用
facets
gem,并需要
string/interpolate
方法


line\u item\u interpolated=String.interpolate{line\u item}

我的方法需要包含要插值的变量的字符串作为输入。这不是像你那样硬编码的。这是一个挑战。哦,等等,也许我没有遵循。收益率做什么?这是一个危险的领域。你可以使用
eval
,但你永远不应该评估一个你不能100%确定是安全的字符串。W你的模板字符串是从哪里来的?它们的变量选择是否有限?模板可能会工作,特别是像Liquid这样的安全模板。
yield
为块提供值。理论上,在方法中,没有用户输入需要插值的内容。我正在阅读关于facets gem的文章,它提供了一个interpolate字符串方法,但仍然不清楚。