gpt4 book ai didi

ruby-on-rails - rails : Split and wrap each character in a string?

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:35 25 4
gpt4 key购买 nike

我有这样的东西:

<%= @votes %>

只输出一个字符串,如:

123

有没有一种简单的方法可以用一些带有帮助程序的 html 来包装每个字符?

<span class="outerclass">
<span class="innerclass">
1
</span>
</span>

<span class="outerclass">
<span class="innerclass">
2
</span>
</span>

<span class="outerclass">
<span class="innerclass">
3
</span>
</span>

最佳答案

你可以创建一个类似这样的助手:

def wrap_each_char(string, &block)
string.each_char.map(&block).join
end

然后像这样使用它(erb):

<%- @votes = "123" -%>
<%- wrap_each_char(@votes) do |c| -%>
<span class="outer"><span class="inner"><%= c %></span></span>
<%- end -%>

更新:上面的例子代表了一种将 block 级内容传递给助手的方法,但值得注意的是,这个特定的例子可以通过使用 each_char 来简化字符串上的方法并完全避免帮助程序:

<%- @votes.each_char do |c| -%>
<span class="outer"><span class="inner"><%= c %></span></span>
<%- end -%>

关于ruby-on-rails - rails : Split and wrap each character in a string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2129928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com