检查数组仅包含字符串对象

时间:2019-11-10 13:12:57

标签: ruby-on-rails ruby ruby-on-rails-5

有没有一种比下面更简洁的方法来检查数组是否仅包含String类对象?

a = ['one','twon','three']  # => ["one", "twon", "three"]

b = ['one','twon', 1 ]  # => ["one", "twon", 1]

c = ['one','twon', {one: 1} ]  # => ["one", "twon", {:one=>1}]

def contains_only_string_class(object)
  uniq_a= object.map{ |i| i.class }.uniq          # => [String], [String, Integer], [String, Hash]
  uniq_a.include?(String) & (uniq_a.length == 1)  # => true,     false,             false
end                                               # => :contains_only_string_class

contains_only_string_class(a)  # => true
contains_only_string_class(b)  # => false
contains_only_string_class(c)  # => false

1 个答案:

答案 0 :(得分:5)

使用all?

def contains_only_string_class(collection)
  collection.all? { |obj| obj.is_a?(String) }
end