我需要一些Ruby数组柔术的帮助。
我有一个名为@tasks的数组:
[#<PivotalTracker::Story:0x007f9d6b8 @id=314, @url="http://www.pivotaltracker.com/", @created_at=#<DateTime: 2012-06-18T20:23:42+00:00 ((2456097j,73422s,0n),+0s,2299161j)>, @accepted_at=nil, @project_id=357031, @name="Test ", @description="This is the description for \"Test\"", @story_type="feature", @estimate=-1, @current_state="unstarted", @requested_by="joe jones", @owned_by=nil, @labels=nil, @jira_id=nil, @jira_url=nil, @other_id=nil, @integration_id=nil, @deadline=nil, @attachments=[]>, #<PivotalTracker::Story:0x007f9d6b8 @id=315, @url="http://www.pivotaltracker.com/", @created_at=#<DateTime: 2012-06-18T20:25:20+00:00 ((2456097j,73520s,0n),+0s,2299161j)>, @accepted_at=nil, @project_id=357031, @name="Test 2", @description="This is the description for \"Test 2\"", @story_type="feature", @estimate=-1, @current_state="unstarted", @requested_by="joe jones", @owned_by=nil, @labels=nil, @jira_id=nil, @jira_url=nil, @other_id=nil, @integration_id=nil, @deadline=nil, @attachments=[]>, #<PivotalTracker::Story:0x007f9d6b8 @id=316, @url="http://www.pivotaltracker.com/story/", @created_at=#<DateTime: 2012-06-18T20:25:26+00:00 ((2456097j,73526s,0n),+0s,2299161j)>, @accepted_at=nil, @project_id=357031, @name="Test 3", @description="Description for Test 3 ", @story_type="feature", @estimate=-1, @current_state="unstarted", @requested_by="joe jones", @owned_by=nil, @labels=nil, @jira_id=nil, @jira_url=nil, @other_id=nil, @integration_id=nil, @deadline=nil, @attachments=[]>] 我的最终目标是在我的.erb视图中使用上述数组中的ID值创建一个JavaScript数组。
我在考虑尝试一下这样的方法:
var myJSArray = [<%= @tasks.each { |t| print t.id.to_s+", " } %>];然而,这显然会在字符串的末尾附加一个",“,这是不可取的(即它返回"314,315,316,”。这看起来也像是一种黑客行为,并不是正确的做法。
有没有关于如何正确做这件事的想法?
谢谢!
更新:在对SO进行了更多的研究之后,似乎我可以通过两个步骤来完成这项工作:
@ids = @tasks.map { |t| t.id }然后在视图中使用它:
var myJSArray = [<%= @ids.map(&:to_s).join(", ") %>];然而,我不确定这是不是理想的,或者是否可以在一个步骤中完成。
发布于 2012-06-26 00:08:18
var myJSArray = [<%= j @tasks.map(&:id).join(',') %>];或者你可能更喜欢这样的东西:
var myJSArray = <%= @tasks.map(&:id).to_json %>;发布于 2012-06-26 00:07:30
使用Array#join:
<%=print @task.map {|t| t.id.to_s}.join(', ') %>https://stackoverflow.com/questions/11192939
复制相似问题