Image for post
Image for post

Ops Scripting w. Ruby: Frequency 2

Tracking Frequency in Ruby: Part II

Updated: 2020–05–24

The Solutions

These solutions we’ll use a conditional while loop in conjunction with the gets method. The gets will return false once it gets an EOL (end-of-line) marker, otherwise, it returns true.

Solution 1: Conditionally Initialize new Hash Value

We open the file and iterate line by line in this example:

line = line.chomp            # strip newline
line_items = line.split(/:/) # split up line by ':' divider
shell = line_items[6] # slice off 7th item
shell = (line.chomp.split(/:/))[6]
if shell != nil
# do stuff with that shell, using shell string as a key
# initialize new key if key doesn't exist in hash
if ! counts.has_key? shell
counts[shell] = 0
# increment the count
counts[shell] += 1
counts[shell] = counts.has_key?(shell) ? counts[shell] += 1 : 1

Solution 2: Auto Assign a Default Value

Instead of conditionally setting the frequency count with branch logic, we can use ruby’s ||= operator, which sets a default value for a key that does not yet exist..

counts[shell] = (counts[shell] ||= 0) + 1
counts[shell] = (counts[shell] ||= 0) + 1 if shell != nil

Solution 3: Hash with Default Value

Another method is to just to set all keys that do not yet exist to have a default. We can do this with the method instead of {} to create an empty hash.


From these solutions, the you should have picked up the following takeaways for Ruby:

  • Splitting a String
  • List Slicing (or indexing in this case)
  • Testing variable is initialized
  • 3 ways to initialize default value in hash class

Written by

Linux NinjaPants Automation Engineering Mutant — exploring DevOps, Kubernetes, CNI, IAC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store