【问题标题】:How can I split a string in Ruby on Rails and transform it into a list of values如何在 Ruby on Rails 中拆分字符串并将其转换为值列表
【发布时间】:2021-03-09 20:33:03
【问题描述】:

这是我的代码,我试图用这个字符“-”分割一个字符串,它是@recipe.ingredient 的结果,并将该值存储到一个数组中。然后我想遍历该数组并将每种成分显示为单独的行或列表。我的代码没有打印出任何东西。它只打印项目符号点,但不打印数组的值。有人能告诉我我的代码有什么问题以及它是如何工作的吗?

<%= @recipe.ingredient %>
  <% ingredients_array = (@recipe.ingredient).split("-")%>
  <%  ingredient_new = ingredients_array.map(&:to_s) %>
  <%= print ingredient_new %>
    <% ingredient_new.each do |ingredient|  %>
      <li><%=print ingredient %></li>
    <%end %>

This is the view of the code

【问题讨论】:

  • print ingredient 打印到标准输出,但返回值为nil。你可能想要的是&lt;%= ingredient %&gt;。 &lt;%= ... %&gt; 显示表达式的值,而不是发送到标准输出的内容。
  • 谢谢它的工作,我只需要删除打印,这已经是这个
  • "我的代码没有打印出任何东西。" – 可以显示控制台的输出吗?我很确定它确实打印了一些东西。

标签: arrays ruby list split


【解决方案1】:

把下面的方法放到你的帮助文件中

def ingredients_helper(recipe)
  ingredients = recipe.ingredient
                      .split("-")
                      .map(&:to_s)
  content_tag(:ul) do    
    ingredients.each do |ingredient|
      concat(content_tag(:li, ingredient))
    end
  end
end

在您的 erb 文件中使用以下代码

<%= ingredients_helper(@recipe) %>  

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 2010-11-01
    • 2014-05-14
    • 2017-01-13
    • 1970-01-01
    • 2019-03-25
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多