我正在使用Ruby 2.4。我知道如何通过执行
检查字符串是否全部大写str == str.upcase
但是如果我有一个字符串数组,那么检查只有数组的最后一个元素是大写的快速方法是什么,而对于其他元素,str!= str.upcase。我假设数组中至少有一个元素,如果只有一个元素并且它是大写的,我希望我的条件评估为真。
答案 0 :(得分:6)
def only_last_upcase?(arr)
arr.find_index { |w| w == w.upcase } == arr.size - 1
end
only_last_upcase? ["word", "wOrD", "WORD"] #=> true
only_last_upcase? ["WORD", "wOrD", "WORD"] #=> false
only_last_upcase? ["word", "wOrD", "word"] #=> false
only_last_upcase? ["word"] #=> false
only_last_upcase? ["Word"] #=> false
only_last_upcase? ["WORD"] #=> true
only_last_upcase? [] #=> false
答案 1 :(得分:2)
关于Ruby的好处是,将问题的文本描述转换为实际代码相当容易:
def only_last_upcase?(arr)
last_index = arr.size - 1
arr.find_index { |s| s =~ /^[A-Z]*$/ } == last_index
end
他们都有以下结果:
only_last_upcase?(["word", "wOrD", "WORD"])
#=> true
only_last_upcase?(["WORD", "wOrD", "WORD"])
#=> false
only_last_upcase?(["word", "wOrD", "word"])
#=> false
only_last_upcase?(["word"])
#=> false
only_last_upcase?(["WORD"])
#=> true
only_last_upcase?([])
#=> false
答案 2 :(得分:1)
仅检查一个元素是否满足条件和数组的 last 元素满足相同条件:
arr.one? { |str| str == str.upcase } && arr.last == arr.last.upcase
通过Cary Swoveland在答案中给出的所有相同测试。
答案 3 :(得分:0)
一种方法:
</tbody>
另一种方式(看起来更像红宝石?):
def check_only_last_upcase(arr)
return false if arr.empty?
arr.each_with_index do |word, index|
return false if word == word.upcase && index != (arr.length-1)
end
(arr.last.upcase == arr.last)
end
puts check_only_last_upcase(["word", "wOrD", "WORD"]) #true
puts check_only_last_upcase(["WORD", "wOrD", "WORD"]) #false
puts check_only_last_upcase(["word", "wOrD", "word"]) #false
puts check_only_last_upcase(["word"]) #false
puts check_only_last_upcase(["WORD"]) #true
puts check_only_last_upcase([]) #false
最后的建议假设def check_only_last_upcase(arr)
arr.last == arr.last.upcase &&
arr
.slice(0,arr.length-1)
.all? { |word| word.upcase != word }
end
始终至少有一个项目(如果arr
为空则不返回),正如您所指出的那样。
答案 4 :(得分:0)
或者,可能:
foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
和...
2.3.1 :001 > foo = ["WORD","Word"]
=> ["WORD", "Word"]
2.3.1 :002 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> false
2.3.1 :003 > foo = ["WORD","WORD"]
=> ["WORD", "WORD"]
2.3.1 :004 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> false
2.3.1 :005 > foo = ["Word","WORD"]
=> ["Word", "WORD"]
2.3.1 :006 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> true
2.3.1 :007 > foo = ["Word","WORD","WORD"]
=> ["Word", "WORD", "WORD"]
2.3.1 :008 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> false
2.3.1 :009 > foo = ["WORD"]
=> ["WORD"]
2.3.1 :010 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> true
2.3.1 :011 > foo = ["Word"]
=> ["Word"]
2.3.1 :012 > foo.last == foo.last.upcase and foo.select{|e| e == foo.last}.length == 1
=> false