user7055375
user7055375

Reputation:

How do I figure out the percentage of elements in my array whose value is between 1 and 100?

I'm using Ruby 2.4. I have a data array that has a bunch of strings ...

["a", "1", "123", "a2c", ...]

I can check the percentage of elements in my array that are exclusively numbers using

data_col.grep(/^\d+$/).size / data_col.size.to_f

but how do I check the percentage of elements taht are numbers and whose value falls between 1 and 100?

Upvotes: 1

Views: 89

Answers (2)

akuhn
akuhn

Reputation: 27793

Try this

1.0 * array.map(&:to_i).grep(1..100).size / array.size

How does this work?

  • grep accepts any pattern that responds to ===
  • Range#=== is defined as membership check

Upvotes: 1

Ursus
Ursus

Reputation: 30056

Try something like

data_col.grep(/^\d+$/).count { |item| item.to_i.between?(1, 100) } / data_col.size.to_f

Upvotes: 2

Related Questions