Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.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 如何将同一索引处的数组字符保存到另一个数组中?_Ruby_Arrays_Replace - Fatal编程技术网

Ruby 如何将同一索引处的数组字符保存到另一个数组中?

Ruby 如何将同一索引处的数组字符保存到另一个数组中?,ruby,arrays,replace,Ruby,Arrays,Replace,必须有一种简单的方法来替换Ruby中数组的元素。我不想使用正则表达式 while @word_array.include? c do idx = @word_array.index(c) @currently_found[idx] = c @word_array.index(idx) = " " end 我想将字符c保存在同一个索引中,但保存在另一个数组中。只需使用的返回值。例如: an_array = %w[a b c] new_array = [] chars

必须有一种简单的方法来替换Ruby中数组的元素。我不想使用正则表达式

while @word_array.include? c do
  idx = @word_array.index(c)
  @currently_found[idx] = c
  @word_array.index(idx) = " "
end

我想将字符c保存在同一个索引中,但保存在另一个数组中。

只需使用的返回值。例如:

an_array     = %w[a b c]
new_array    = []
chars        = ['b']
chars.each do |char|
  new_array[an_array.index(char)] = char if an_array.include? char
end
new_array
=> [nil, "b"]

不确定您想要它做什么(您真的想将@word\u数组更改为包含空格吗?),但这应该可以做到(除了数组末尾的其他零,不知道这是否是个问题):

@current_found=@word_array.map{| w | w==c?c:nil}