Skip to content

Instantly share code, notes, and snippets.

@dbrady
Created April 19, 2016 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbrady/4ee91acc128d0d5135a6cc02b1c163c7 to your computer and use it in GitHub Desktop.
Save dbrady/4ee91acc128d0d5135a6cc02b1c163c7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'debug_inspector'
def find_matchers(keys)
matchers = []
matcher_suffixes = ["IS"]
keys.any? do |key|
matcher_suffixes.any? do |suffix|
var = "%s_%s" % [key.upcase, suffix]
matchers << [var, ENV[var]] if ENV.key?(var)
end
end
matchers
end
def should_i_yield? hash
matchers = find_matchers(hash.keys)
matchers.empty? || matchers.all? {|m| matches?(m, hash) }
end
def matches?(matcher, hash)
name, value = *matcher
if name.end_with?("_IS")
key = name[0...-3].downcase.to_sym
hash[key] == ENV[name]
end
end
def iterate_interestingly ray, &block
ray.each do |hash|
next unless should_i_yield?(hash)
yield *hash.values
end
end
# run this with "ruby ./interesting.rb" for full output
# run this with "NAME_IS=Dave ruby ./interesting.rb" to just see Dave
# run this with "AGE_GE=18 ruby ./interesting.rb" to see adults
# run this with "NAME_IS=Dave AGE_GE=18 ruby ./interesting.rb" to see adults named Dave
iterate_interestingly([
{ name: "Alice", age: 19 },
{ name: "Bob", age: 16 },
{ name: "Carol", age: 17 },
{ name: "Dave", age: 45 },
{ name: "Dave", age: 15 },
]) do |name, age|
puts "User #{name} is #{age} years old."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment