如何检索数组中元素的不同位置

时间:2015-09-23 14:11:34

标签: arrays ruby

我想检索一个包含数组中元素(不仅是第一个)位置的数组。例如,在以下数组中:

["blue", "red", "blue", "blue", "red"]

当我将[0, 2, 3]作为参数传递时,我想检索"blue"。据推测,如果元素在数组中没有,则该函数应返回nil

4 个答案:

答案 0 :(得分:3)

result = ["blue", "red", "blue", "blue", "red"]
.to_enum.with_index.select{|e, _| e == "blue"}.map(&:last)
result = nil if result.empty?
result # => [0, 2, 3]

答案 1 :(得分:2)

a = ["blue", "red", "blue", "blue", "red"]
result = a.map.with_index{|e,i| i if e == "blue"}.compact
=>[0,2,3]
result = nil if result.empty?

答案 2 :(得分:2)

def offsets(arr, target)
  off = arr.each_index.select { |i| arr[i]==target }
  off.empty? ? nil : off
end

colors = %w| blue red blue blue red |

offsets(colors, "blue")
  #=> [0,2,3]
offsets(colors, "chartreuse")
  #=> nil

也可以写:

def offsets(arr, target)
  arr.index(target) && arr.each_index.select { |i| arr[i]==target }
end

答案 3 :(得分:1)

方法定义:

def diff_pos arr, key
  result = arr.each_with_index.map { |el,i| i if el == key }.compact
  result.empty? ? nil : result
end

执行:

x = ["blue", "red", "blue", "blue", "red"]
diff_pos(x, "blue")
# => [0, 2, 3]