Ruby:如何存储和显示一周中的某一天? [英] Ruby: How to store and display a day of the week?
问题描述
我对 Ruby 比较陌生.我需要在我的活动模型中跟踪一周中的某一天.到目前为止,我拥有的代码似乎不是最优雅的解决方案.我想知道是否有更好的方法.
到目前为止,这是我的表单:
<%= form_for(@activity) do |f|%><div class="field"><%= f.label :day%><br/><%= f.select :day, [['Sunday', 0], ['Monday', 1], ['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['星期五', 5], ['星期六', 6]] %>
<%结束%>
当我需要显示星期几时:
<% days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] %><% @activities.each 做 |activity|%><%=天[activity.day.to_i]%><%结束%>
我怎样才能做得更好?随意提及我可能不知道的任何图书馆/宝石.
解决方案:
Ruby 提供了 Date::DAYNAMES
常量,它是一周中的天数数组.我们可以在我们的代码中重用它:
<%= form_for(@activity) do |f|%><div class="field"><%= f.label :day%><br/><%= f.select :day, Date::DAYNAMES.zip((0..6).to_a) %>
<%结束%><% @activities.each 做 |activity|%><%= 日期::DAYNAMES[activity.day.to_i] %><%结束%>
Ruby 的 Date
类已经定义了一个常量,用于在数组中保存日期的名称:Date::DAYNAMES
.
例如,您可以执行以下操作:
days = []日期::DAYNAMES.each_with_index { |x, i|天<<[x, i] }
我不知道我是否一定要说这更好,但您绝对可以利用现有的东西.
I'm relatively new to Ruby. I need to keep track of a day of the week on my activity model. The code that I have so far doesn't seem like the most elegant solution. I am wondering if there is a better way.
So far, this is what I have in my form:
<%= form_for(@activity) do |f| %>
<div class="field">
<%= f.label :day %><br />
<%= f.select :day, [['Sunday', 0], ['Monday', 1], ['Tuesday', 2], ['Wednesday', 3], ['Thursday', 4], ['Friday', 5], ['Saturday', 6]] %>
</div>
<% end %>
And when I need to display the day of the week:
<% days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] %>
<% @activities.each do |activity| %>
<%= days[activity.day.to_i] %>
<% end %>
How can I do this better? Feel free to mention any library/gem that I may not be aware of.
Solution:
Ruby provides the Date::DAYNAMES
constant which is an array of days of the week. We can reuse that in our code:
<%= form_for(@activity) do |f| %>
<div class="field">
<%= f.label :day %><br />
<%= f.select :day, Date::DAYNAMES.zip((0..6).to_a) %>
</div>
<% end %>
<% @activities.each do |activity| %>
<%= Date::DAYNAMES[activity.day.to_i] %>
<% end %>
Ruby's Date
class already has a constant defined that holds the name of the days in an array: Date::DAYNAMES
.
For example, you could do something like:
days = []
Date::DAYNAMES.each_with_index { |x, i| days << [x, i] }
I don't know if I'd necessarily say that this is better, but you can definitely leverage what is already available to you.
这篇关于Ruby:如何存储和显示一周中的某一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!