Created
April 19, 2016 22:33
-
-
Save dbrady/4ee91acc128d0d5135a6cc02b1c163c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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