each_element 的行为不符合预期
当我在 irb 中时,我做了这样的事情:
node_list.each_element { |e| puts e.text }
它可以工作并为每个返回的元素打印一行文本(另外我认为它返回 xml 对象)。然而,当我转向 Rails 并让东西在控制器、助手、视图和布局之间移动时,它只会转储 xml 对象。
我应该提到的是,我使用 Rails 1.2.3 和 ruby 1.8.7 是有充分理由的。
谢谢!
When I'm in irb and I do something like this:
node_list.each_element { |e| puts e.text }
It works and prints one line of text per element returned (plus I think it returns the xml object). However, when I head over to rails and have things moving between controllers, helpers, views and layouts it just dumps the xml object.
I should mention that for good reasons I'm using rails 1.2.3 and ruby 1.8.7.
Gratzi!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以您遇到的问题是将写入写入控制台而不是模板。另外,在 ruby 中, a 方法将默认返回其最后一个对象。因此,您编写的方法将循环遍历 @child1,将每个文本打印到控制台,然后返回 @child1 对象,此时您的 erb 标签 <%= %>;告诉它打印对象(在本例中为@child1)
您有两个选择,或者可以将其移到模板中:
或者构建您的方法,以便它循环构建一个字符串,然后返回该字符串而不是原始对象:
您可以通过多种方式编写此类方法,但这是我常用的方式。
So the issue your having is that puts writes to console and not the template. Also, in ruby the a method will return by default its last object. So your method as written will loop through @child1, print each's text to the console, and then return the @child1 object at which point your erb tags of <%= %> tells it print the object (@child1 in this case)
You have two options, either you can move it out into the template:
Or build your method so that it loops through building a string and then returns that string instead of the original object:
Several ways you could write this type of method, but this is my usual way.