Ruby on rails 基于价值包含不同内容的更优雅方式

Ruby on rails 基于价值包含不同内容的更优雅方式,ruby-on-rails,arrays,ruby,Ruby On Rails,Arrays,Ruby,是否有一种更优雅的方法来编写此代码,可以通过定义数组[[1,“test1”],[2,“test2”],…] <%- if c.current_state == 1 %> Test1 <% elsif c.current_state == 2 %> Test2 <% elsif c.current_state == 3 %> Test3 <% elsif c.current_state == 4 %> Test4 <% elsif c.curr

是否有一种更优雅的方法来编写此代码,可以通过定义数组
[[1,“test1”],[2,“test2”],…]

<%- if c.current_state == 1 %>
Test1
<% elsif c.current_state == 2 %>
Test2
<% elsif c.current_state == 3 %>
Test3
<% elsif c.current_state == 4 %>
Test4
<% elsif c.current_state == 5 %>
Test5
<% elsif c.current_state == 6 %>
Test6
<% end %>

测试1
测试2
测试3
测试4
测试5
测试6

在您看来,您只需使用

Test<%= c.current_state %>
我会给你

["test1", "test2", "test3", "test4", "test5", "test6"]
{1=>"test1", 2=>"test2", 3=>"test3", 4=>"test4", 5=>"test5", 6=>"test6"}
使用带有索引的映射

1.upto(6).map.with_index {|v| [v, "test#{v}"] }
将为您提供所需的阵列

[[1, "test1"], [2, "test2"], [3, "test3"], [4, "test4"], [5, "test5"], [6, "test6"]]
使用

我会给你

["test1", "test2", "test3", "test4", "test5", "test6"]
{1=>"test1", 2=>"test2", 3=>"test3", 4=>"test4", 5=>"test5", 6=>"test6"}

您可以从代码中没有神秘数字开始。也许make
current\u state
返回一个Ruby符号。如果你的代码有效,请考虑将其移动到。不要对试图帮助你的人无礼。@theTinMan这个问题,以其当前形式,过于抽象、假设和不清楚,不符合代码审查的条件。