繁体   English   中英

从Ruby数组中获取特定值并创建逗号分隔的字符串

[英]Fetching specific values from Ruby array and creating a comma-delimited string

我需要一些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(", ") %>];

但是,不确定这是否理想还是可以一步完成。

var myJSArray = [<%= j @tasks.map(&:id).join(',') %>];

或者您可能更喜欢这样的事情:

var myJSArray = <%= @tasks.map(&:id).to_json %>;

使用Array#join

<%=print @task.map {|t| t.id.to_s}.join(', ') %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM