我有一个随机顺序的两个值的数组。我想找到另一个值是什么,并把它变成一个字符串。
这就是我目前在Ruby中所拥有的,但我正试图将其清理干净,使其更加简洁。
array = ["garden_shop","some_value"]
tag = array.delete("garden_shop")
@tag = tag.first
这应导致:
@tag = "some_value"
使用-
操作符:
@tag = (array - ["garden_shop"]).first
资料来源:https://ruby-doc.org/core-2.2.0/Array.html#method-i-2D
相关:如何按值从数组中删除一个元素
看起来search
正是你想要的:
array.find {|v| v != 'garden_shop'}
#=> "some_value"
我会用:
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