简体   繁体   English

从Ruby on Rails块输出代码而无需关闭ruby标签

[英]Output code from Ruby on Rails block without closing ruby tags

Ok this may seem stupid and I have googled extensively using various different keywords and terms, attempted a lot of various different methods and tried to my very last breadth and cannot seem to figure out how to do this. 好的,这似乎很愚蠢,我使用各种不同的关键字和术语在Google上进行了广泛的搜索,尝试了多种不同的方法,并尝试了最后的广度,但似乎无法弄清楚该怎么做。 All I want is stdout in a rails app without needing to break my block. 我所需要的只是在Rails应用程序中输出而不需要中断我的程序。

Currently, when I do a block of ruby code in my rails app and want to output the value I do the following 当前,当我在Rails应用程序中执行红宝石代码块并想输出值时,请执行以下操作

<% somearray do | item | %>
    <%= item %>
<% end %>

To me this is quite messy, I know coming from a PHP background it's not how one should imagine how to code in rails but coming from many different environments I like my code to look nice to me . 对我来说,这很混乱,我知道来自PHP背景,这不是应该想象如何在Rails中编码的方法,而是来自许多不同的环境,我喜欢我的代码对我来说看起来不错。 It's very easy to encapsulate every single line with <% %> but I'd prefer my code to be my code and my mark up to be my mark up. 用<%%>封装每一行非常容易,但是我希望我的代码是我的代码,而我的标记是我的标记。

What I'd like, but which doesn't work, is.... 我想要的是,但是没有用的是...。

<%
    somearray do | item |
        whatever item #whatever being puts or similar
    end
%>

It's solely for the aesthetics of the code and not for what it produces but for me, a very long time programmer, it means a lot and a lot of time saved when trying to see where and when code blocks begin and end. 这仅仅是出于代码的美感,而不是代码的产生,而是对我来说,这是一个很长的程序员,这意味着在尝试查看代码块的开始位置和结束时间时,可以节省大量时间。

Thanks in advance, 提前致谢,

Jay (c0ld) 周杰伦(c0ld)

You can use concat . 您可以使用concat From the docs : 文档

The preferred method of outputting text in your views is to use the <%= “text” %> eRuby syntax. 在视图中输出文本的首选方法是使用<%= “text” %> eRuby语法。 .... If you absolutely must output text within a non-output code block (ie, <% %> ), you can use the concat method. ....如果绝对必须在非输出代码块(即<% %> )中输出文本,则可以使用concat方法。

Examples 例子

 <% concat "hello" # is the equivalent of <%= "hello" %> if logged_in concat "Logged in!" else concat link_to('login', :action => login) end # will either display "Logged in!" or a login link %> 

What about... 关于什么...

<%= somearray.map {|item| item }.join(" ") %>

PS of course if item just outputs itself - it can be even shorter PS,当然,如果项目只是输出自身-甚至可以更短

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

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