我需要一些有關Ruby數組jujitsu的幫助。從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視圖中的JavaScript數組只以上數組中的ID值。
我想嘗試這樣的:
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(", ") %>];
不知道這是理想的,或者它可以做盡管如此,只需一步。
+1 for'to_json' – robbrit
謝謝!當我不包含「j」時,第一個變體工作 - 不知道爲什麼那裏有? – tonic
第二個實際上引起了問題。挖掘進一步...... – tonic