如何计算数组中字符串的平均长度?

时间:2017-05-25 16:29:30

标签: arrays ruby string average string-length

如何计算数组中字符串的平均长度?我以为我能做到

2.4.0 :004 >   arr = ["a", "ab", "abc"]
 => ["a", "ab", "abc"]
...
2.4.0 :006 > arr.inject{ |sum, el| sum + el.length }.to_f / arr.size
TypeError: no implicit conversion of Integer into String
    from (irb):6:in `+'
    from (irb):6:in `block in irb_binding'
    from (irb):6:in `each'
    from (irb):6:in `inject'
    from (irb):6
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/console.rb:65:in `start'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/console_helper.rb:9:in `start'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `my_command!'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

但显然不是。

4 个答案:

答案 0 :(得分:3)

我会这样写:

arr.join.size / arr.size.to_f

此外,您可以在Ruby 2.4之后使用sum

arr.sum(&:size) / arr.size.to_f
#=> 2.0

答案 1 :(得分:3)

Ruby 2.4.0之前

arr.inject(0) { |acc, s| acc + s.length } / arr.size.to_f

Ruby 2.4.0之后

arr.sum(&:length) / arr.size.to_f

答案 2 :(得分:2)

injectsum的起始值。它默认为String。这有效:

arr.inject(0) { |sum, el| sum + el.length }.to_f / arr.size

答案 3 :(得分:2)

以下是一些基准:

require 'fruity'

arr = ["a", "ab", "abc"]

puts "Ruby #{RUBY_VERSION}"

compare do
  ilya1 { arr.join.size / arr.size.to_f }
  ilya2 { arr.sum(&:size) / arr.size.to_f }
  derrell_durrett { arr.inject(0) { |sum, el| sum + el.length }.to_f / arr.size }
  ursus1 { arr.inject(0) { |acc, s| acc + s.length } / arr.size.to_f }
  ursus2 { arr.sum(&:length) / arr.size.to_f }
end

# >> Ruby 2.4.1
# >> Running each test 8192 times. Test will take about 1 second.
# >> ursus2 is similar to ilya2
# >> ilya2 is faster than ilya1 by 2x ± 0.1
# >> ilya1 is similar to ursus1
# >> ursus1 is similar to derrell_durrett

基本上ursus2ilya2是相同的,因为size is an alias of length