什么是打破这个数组的更简单的方法?

时间:2017-04-18 19:22:11

标签: ruby-on-rails ruby

我有一个随机顺序的两个值的数组。 我想找到另一个值是什么,并把它变成一个字符串。

这是我目前在Ruby中所拥有的,但我正在尝试清理它并使其更简洁。

 array = ["garden_shop","some_value"]
 tag = array.delete("garden_shop")
 @tag = tag.first

哪个应该导致:

@tag = "some_value"

3 个答案:

答案 0 :(得分:3)

使用-运算符:

@tag = (array - ["garden_shop"]).first

来源:https://ruby-doc.org/core-2.2.0/Array.html#method-i-2D
相关:How can I delete one element from an array by value

答案 1 :(得分:3)

好像你想要find

array.find {|v| v != 'garden_shop'}
#=> "some_value"

答案 2 :(得分:1)

我使用:

if array.first == 'garden_shop' 
  array.last 
else
  array.first 
end
# => "some_value"

这也可以更简洁地写成:

array.first == 'garden_shop' ? array.last : array.first
# => "some_value"

但它牺牲了可读性。

这可能会有所帮助:

array = ["garden_shop","some_value"]
compare do
  user000001 { (array - ["garden_shop"]).first }
  ilya { array.find {|v| v != 'garden_shop'} }
  ttm {
    if array.first == 'garden_shop' 
      array.last 
    else
      array.first 
    end
  }
end

# >> Running each test 32768 times. Test will take about 2 seconds.
# >> ttm is faster than ilya by 5x ± 1.0
# >> ilya is similar to user000001

而且,只是为了彻底:

compare do
  ttm1 { array.first == 'garden_shop' ? array.last : array.first }
  ttm2 {
    if array.first == 'garden_shop' 
      array.last 
    else
      array.first 
    end
  }
end
# >> Running each test 32768 times. Test will take about 1 second.
# >> ttm1 is similar to ttm2