【问题标题】:How to display contents of global variable in Ruby如何在 Ruby 中显示全局变量的内容
【发布时间】:2018-04-21 04:13:03
【问题描述】:

我是为一堂课写的:

<% if @course.comments.exists? %>
      <h2>Ratings</h2>
      <% $total = 0 %>
      <% @course.comments.each do |comment| %>
        <p>
          <strong>Commenter:</strong>
          <%= comment.commenter %>
        </p>
        <p>
          <strong>Score:</strong>
          <%= comment.score %>
        </p>
        <p>
          <strong>Comment:</strong>
          <%= comment.comment %>
        </p>
        <p>
          <strong>Words in Comment:</strong>
          <%= comment.comment.length %>
        </p>
        <% $total += 1%>
          <%= link_to 'Destroy Rating', [comment.course, comment],
            method: :delete,
            data: { confirm: 'Are you sure?' } %>
        </p>
      <% end %>
    <% else %>
      <h2>No ratings available</h2>
    <% end %>
    <p>
      <strong>Total Comments</strong>
      <%= print $total %>
    </p>

我尝试过 puts 和 print,但我的屏幕上没有显示任何内容。我需要让它计算&lt;% @course.comments.each do |comment| %&gt; 行的每次迭代。 Ruby 不是我的强项,老师也不清楚如何实现这个目标。我对替代品持开放态度。

【问题讨论】:

    标签: html ruby-on-rails ruby variables counter


    【解决方案1】:

    不要使用全局变量,顾名思义,它们是全局变量,这意味着它可以被其他请求/线程更新。

    如果您要查找给定@course 的 cmets 总数,您可以调用@course.cmets.count。这应该会给你你正在寻找的总数。

    【讨论】:

    • 这很有帮助。我需要显示的结果在循环之外,所以我不确定是否需要将其设为全局。我在我的另一堂课上学习了 python,我有点困惑你需要在哪里使用全局变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2020-03-16
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多