Ruby数组有条件地替换数组

时间:2017-06-30 10:20:59

标签: ruby-on-rails arrays ruby

我正在努力构建一个小的ruby片段来比较两个数组并有条件地替换其中一个数组中的项目。 我有一本"书"有标题和标题的模型有章节。我有一个包含书籍所有行的数组,并希望用这个数组中相应的标题替换章节。

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

我想这对阵列没有任何影响,因为我只是把#34;#{book.title}"在没有向数组推送任何东西的情况下排队" all_lines_of_a_book"。有人可以帮我找到正确的语法吗?

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

这种方法可能有所帮助:

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] 

答案 2 :(得分:0)

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 }