简体   繁体   English

这个简单的方法在Rails助手中不起作用

[英]This simple method doesn't work in Rails helper

Hey guys I'm new to rails. 大家好,我是新手。 I'm practice what I've learned today about rails helper and ruby blocks by writing this code: 我正在通过编写以下代码来练习我今天所学到的有关Rails辅助程序和ruby块的知识:

in /apps/helpers/home_helper.rb 在/apps/helpers/home_helper.rb中

module HomeHelper
  def each(from, to, by)
    x = from
    while x <= to
      yield x
      x = x + by
    end
  end
end

in /apps/views/index.html.erb 在/apps/views/index.html.erb中

<p><%= each(2,16,3){|x| x } %></p>

But after I run the server, and navigate to the localhost:3000/home/index nothing in there. 但是在我运行服务器之后,导航到localhost:3000 / home / index那里什么也没有。

anybody tells me what did I do wrong? 有人告诉我我做错了什么吗? Thanks 谢谢

As other people have said, there are better methods fro what you're trying to achieve built into ruby. 就像其他人说的那样,有很多更好的方法可以实现内置的红宝石。 Specifically the #step method: 特别是#step方法:

2.step(16, 3) { |i| puts i }

Also note that your index.html.erb file should have been in apps/views/home . 另请注意,您的index.html.erb文件应该位于apps/views/home

You don't need to write that method. 您无需编写该方法。 Do this instead: 改为这样做:

<% [2, 16, 3].each do |n| %>
 <p><%= n %></p>
<% end %>

The reason for this, is that the method 'each' 1) is already a Ruby method on any Enumerable object and 2) it is poor practice to re-invent such a basic wheel. 这样做的原因是,方法“每个” 1)在任何Enumerable对象上已经是Ruby方法,并且2)重新发明这种基本的轮子是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM