【问题标题】:Ruby array conditionnally replacing an item in an arrayRuby 数组有条件地替换数组中的项目
【发布时间】:2017-06-30 10:20:59
【问题描述】:

我正在努力构建一个小型 ruby​​ sn-ps 来比较两个数组并有条件地替换其中一个数组中的项目。 我有一个“书”模型,它有标题,标题有章节。我有一个包含一本书所有行的数组,想用这个数组中的相应标题替换章节。

def replace_chapters_by_titles(all_lines_of_a_book)
  books = Book.all
  all_lines_of_a_book.each do |line|
    books.each do |chapter|
    if (line =~ /#{book.chapter}/)
    line = "#{book.title}" #this is where I am not sure what I should do
    end
    end
  end
end

我猜这对数组没有影响,因为我只是将“#{book.title}”放入队列中,而不向数组“all_lines_of_a_book”推送任何内容。有人可以帮我找到正确的语法吗?

【问题讨论】:

  • 这里有什么书?你会得到一个未定义的变量或方法“book”错误。 books 的迭代器可以是 book 而不是 chapter
  • 哦,是的,这本书是未定义的..请照顾好它

标签: ruby-on-rails arrays ruby


【解决方案1】:

你需要推送到数组中存在行的索引,试试下面的代码

def replace_chapters_by_titles(all_lines_of_a_book)
  books = Book.all
  all_lines_of_a_book.each_with_index do |line, index| # note this
    books.each do |chapter|
      if (line =~ /#{book.chapter}/)
        all_lines_of_a_book[index] = "#{book.title}" # and this
      end
    end
  end
  all_lines_of_a_book # probably you want to return new array
end

【讨论】:

    【解决方案2】:

    这种方法可能会有所帮助:

    arr   # => [1, 22, 5, 66, 77, 8, 88, 0] 
    subst # => [9,  8, 7,  6,  5, 4,  3, 2]
    cond = lambda { |x| x>10 } # condition for substitution
    arr.zip(arr.map(&cond)).each_with_index.map do |(a,b),i| 
      if b then subst[i] else a end 
    end # => [1, 8, 5, 6, 5, 8, 3, 0] 
    

    【讨论】:

      【解决方案3】:
      arr   # => [1, 22, 5, 66, 77, 8, 88, 0] 
      subst # => [9,  8, 7,  6,  5, 4,  3, 2]
      
      arr.each_index.map { |i| arr[i] > 10 ? subst[i] : arr[i] }
        # => [1, 8, 5, 6, 5, 8, 3, 0]
      

      arr.each_with_index.map { |n,i| n > 10 ? subst[i] : n }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2018-02-14
        • 2011-08-20
        • 1970-01-01
        相关资源
        最近更新 更多