[英]This simple method doesn't work in Rails helper
大家好,我是新手。 我正在通过编写以下代码来练习我今天所学到的有关Rails辅助程序和ruby块的知识:
在/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
在/apps/views/index.html.erb中
<p><%= each(2,16,3){|x| x } %></p>
但是在我运行服务器之后,导航到localhost:3000 / home / index那里什么也没有。
有人告诉我我做错了什么吗? 谢谢
就像其他人说的那样,有很多更好的方法可以实现内置的红宝石。 特别是#step方法:
2.step(16, 3) { |i| puts i }
另请注意,您的index.html.erb
文件应该位于apps/views/home
。
您无需编写该方法。 改为这样做:
<% [2, 16, 3].each do |n| %>
<p><%= n %></p>
<% end %>
这样做的原因是,方法“每个” 1)在任何Enumerable对象上已经是Ruby方法,并且2)重新发明这种基本的轮子是不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.