优化这个字符计数器的任何方法,我用 ruby 为 String 类编写


# Character Counter
class String
def count_lcases
count(('a'..'z').to_a.join(''))
end
def count_upcases
count(('A'..'Z').to_a.join(''))
end
def count_num
count((0..9).to_a.join(''))
end
def count_spl_chars
length - count_lcases - count_upcases - count_num
end
end
input = ARGV[0]
if ARGV.empty?
puts 'Please provide an input'
exit
end
puts 'Lowercase characters = %d' % [input.count_lcases]
puts 'Uppercase characters = %d' % [input.count_upcases]
puts 'Numeric characters = %d' % [input.count_num]
puts 'Special characters = %d' % [input.count_spl_chars]

我使用范围来计算字符数,但计数函数被调用了 3 次。

我总是可以使用循环并一一计数。我想知道有什么方法可以优化它?...

如果你使用的是Ruby 2.7,你可以使用tally;字符串的字符只迭代一次。

def classify_char(c)
case c
when /[a-z]/ then :lcase 
when /[A-Z]/ then :ucase
when /d/    then :digit
else :other
end
end
p "asg3456  ERTYaeth".chars.map{|c| classify_char(c) }.tally
# => {:lcase=>7, :digit=>4, :other=>2, :ucase=>4}

如果 Ruby 2.3...2.7,这将起作用:

CHAR_CLASSES = {
lcase: ?a..?z,
ucase: ?A..?Z,
digit: ?0..?9,
}
p "asg3456  ERTYaeth".each_char.with_object(Hash.new(0)) { |c, o|
o[CHAR_CLASSES.find { |label, group| group === c }&.first || :other] += 1
}

对于 <2.3,

p "asg3456  ERTYaeth".each_char.with_object(Hash.new(0)) { |c, o|
p = CHAR_CLASSES.find { |label, group| group === c }
o[p ? p.first : :other] += 1
}

相关内容

最新更新