1

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?

2 Answers2

2

Try something like

data_col.grep(/^\d+$/).count { |item| item.to_i.between?(1, 100) } / data_col.size.to_f
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

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
akuhn
  • 27,477
  • 2
  • 76
  • 91