【问题标题】:Replace elements in an array whose indexes do not match the given indexes替换数组中索引与给定索引不匹配的元素
【发布时间】:2015-01-03 09:03:07
【问题描述】:

我有以下两个变量:

array = ['h','e','l','l','o']
string = '023'

array 中没有与string 中某处匹配的索引的所有元素都需要替换为下划线。新数组应如下所示:['h','_','l','l','_']。

我正在考虑做这样的事情

.map.with_index do |e,i|
  if (i != string) #Somehow get it to check the entire string
    e = '_'
  end
end

【问题讨论】:

  • 你有什么问题?
  • '023' 是否扩展为[0,2,3] 或[0,23]?如果您将其更改为索引数组,问题将会得到改善。

标签: ruby arrays indexing


【解决方案1】:

既然您已经知道要保留的位置,只需将其用作模式:

array = %w[ h e l l o ]
string = '023'

# Create a replacement array that's all underscores
replacement = [ '_' ] * array.length

# Transpose each of the positions that should be preserved
string.split(//).each do |index|
  index = index.to_i

  replacement[index] = array[index]
end

replacement
# => ["h", "_", "l", "l", "_"]

如果您的索引说明符发生变化,您需要重新编写该解析器以进行相应的转换。例如,如果您需要超过 9 的数字,您可以切换到逗号分隔。

【讨论】:

  • 恕我直言,您应该使用each_char 而不是split(//).each
  • 我正在考虑使用它,但是通过切换到 /,/ 来更容易适应逗号分隔的方法。
  • @CarySwoveland 已修复。感谢您注意到这一点。
【解决方案2】:
array = ['h','e','l','l','o']
string = '023' 

当然,第一步是将string 转换为索引数组,它们可能首先应该存储的方式,部分是为了允许使用大于九的索引:

indices = string.each_char.map(&:to_i)
  #=> [0, 2, 3]

一旦完成,就有无数种方法可以进行替换。假设array 不会被变异,这里有一个非常简单的方法:

indices.each_with_object([?_]*array.size) { |i,arr| arr[i] = array[i] }
  #=> ["h", "_", "l", "l", "_"]

如果您愿意,可以将这两行合并:

string.each_char.map(&:to_i).each_with_object([?_]*array.size) do |i,arr|
  arr[i] = array[i]
end

或者,

string.each_char.with_object([?_]*array.size) do |c,arr|
  i = c.to_i
  arr[i] = array[i]
end

【讨论】:

  • 我真的很喜欢indices.each_with_object([?_]*array.size) { |i,arr| arr[i] = array[i] } 行。赞一个。
【解决方案3】:
 array.map.with_index{|x,i|!string.include?(i.to_s)?'-':x}

【讨论】:

    【解决方案4】:

    这是我的解决方案:

    string = %w[ h e l l o ]
    indexes = '023'
    
    (
      0.upto(string.size - 1).to_a -
      indexes.each_char.map(&:to_i)
    ).each do |i|
      string[i]= '_'
    end
    
    puts string.inspect
    # => ["h", "_", "l", "l", "_"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 2022-01-02
      • 2012-11-19
      • 2021-08-31
      • 2017-11-26
      • 2019-10-12
      • 2017-08-06
      • 2020-11-07
      相关资源
      最近更新 更多