我正在努力构建一个小的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我猜这对数组没有影响,因为我只是将"#{book.title}“放在一行中,而没有将任何东西推入数组"all_lines_of_a_book”。有人能帮我找到正确的语法吗?
发布于 2017-06-30 18:29:11
您需要推送到数组中行所在的索引,请尝试下面的代码
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发布于 2017-06-30 18:32:12
这种方法可能会有所帮助:
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] 发布于 2017-07-01 00:03:32
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 }https://stackoverflow.com/questions/44844164
复制相似问题