Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在递归调用期间获取当前索引_Ruby On Rails_Ruby_Ancestry - Fatal编程技术网

Ruby on rails 如何在递归调用期间获取当前索引

Ruby on rails 如何在递归调用期间获取当前索引,ruby-on-rails,ruby,ancestry,Ruby On Rails,Ruby,Ancestry,我使用gem祖先创建注释 现在,我可以列出所有评论 但我想把序列号推到每条评论上 例如,如果有3条注释,第一条注释由1注释,下一条注释由2注释 我不知道怎么做 show.html.haml 帮手 每个带有索引的\u在递归上都不起作用 如果我有4条评论,我想为每条评论显示0,1,2,3 但是每一个带有索引的_都不能实现它,因为它是一个递归调用 comments.each_with_index.map do |(comment, sub_comments), i| 评论 =>{#=> {#=> {

我使用gem
祖先
创建注释

现在,我可以列出所有评论

但我想把序列号推到每条评论上

例如,如果有3条注释,第一条注释由1注释,下一条注释由2注释

我不知道怎么做

show.html.haml 帮手 每个带有索引的\u在递归上都不起作用 如果我有4条评论,我想为每条评论显示0,1,2,3

但是每一个带有索引的_都不能实现它,因为它是一个递归调用

comments.each_with_index.map do |(comment, sub_comments), i|
评论
=>{#=>
{#=>
{#=>
{},
#=>
{}}}}

ruby中的每个可枚举实例都有一个方法,提供一个\u枚举器。因此,在您的情况下,我建议使用:

- comments.map do |comment, sub_comments|
+ comments.each_with_index.map do |idx, comment, sub_comments|

希望对您有所帮助。

您可以将
与_index一起使用
与map一起使用

comments.map.with_index do |comment, sub_comments, index|

我不知道有什么好办法。但是您可以将计数器传递到
嵌套的_注释
函数中,并手动处理问题——这可能意味着根本不需要
映射
。丑陋,我知道

举一个简单的例子,如果您需要:

def nested_foo(result, string, index)
  index += 1
  result << "\n#{index}: #{string}"

  if index >= 10
    return result
  else
    return nested_foo(result, string, index)
  end

end
def嵌套_foo(结果、字符串、索引)
指数+=1
结果=10
返回结果
其他的
返回嵌套的_foo(结果、字符串、索引)
结束
结束
- comments.map do |comment, sub_comments|
+ comments.each_with_index.map do |idx, comment, sub_comments|
comments.map.with_index do |comment, sub_comments, index|
def nested_foo(result, string, index)
  index += 1
  result << "\n#{index}: #{string}"

  if index >= 10
    return result
  else
    return nested_foo(result, string, index)
  end

end