Image for post
Image for post

Ops Scripting w. Ruby: Frequency 3

Tracking Frequency in Ruby: Part III

Before we showed how the basics of a frequency hash, building it as we iterate line by line through the file, and how to default a value when reference a key that does not exist.

The Solutions

In previous solutions, we built the data structure, the counts dictionary as we went through each line. This time, we will do it more serially, to where we’ll create a list of shells called shell_list, and then build our counts dictionary from that.

Solution 4: Conditional Shovel

Filter First then Append
File.open('etc/passwd', 'r') do |file|
while line = file.gets
# process each line
end
end
line !~ /:$/
shell_list << line.chomp.split(/:/)[6]
shell_list.uniq.each do |uniq_shell|
counts[uniq_shell] = shell_list.count(uniq_shell)
end

Solution 5: Getting Functional with Map and Select

In this solution, we’ll use a functional approach using map() and select. In ruby, using an iterable list, we can use a select() to filter out items, and a map() to transform the data. These functions accept a block as a parameter, which is then used to process the list.

list = lines | select valid_lines | map 7th_item_sliced
lines_from_file.select { |line| line !~ /:$/ }
lines_from_file.select { |line| line =~ /^.*[^:]$/ }
list_of_valid_lines.map { |line| (line.chomp.split(/:/))[6] }
squares = numbers.map { |num| [num, num**2] }.to_h
capitals = words.map { |word| [word, word.upcase()] }.to_h
shell_list.uniq.map {|s| [s, shell_list.count(s)] }.to_h

About Iterable Blocks

For those unfamiliar with Ruby, you can use either do…end or braces {}:

iterable.each do |i|
list << i
end
iterable.each { |i| list << i }

The Conclusion

Using functional programming with select and map along with blocks are powerful tools within ruby, and can be tricky to get your mind around if exposed to it the first time.

  • Shovel operator << for append
  • Creating list of unique elements with uniq
  • Blocks as parameters with do…end or braces {}
  • map() and select() Functions
  • Creating a hash with map().to_h

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