Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active April 21, 2020 04:08
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 havenwood/0ec15cabfb43365d988a26a9124d2e0d to your computer and use it in GitHub Desktop.
Save havenwood/0ec15cabfb43365d988a26a9124d2e0d to your computer and use it in GitHub Desktop.
Example of implementing a simple #dig for #ruby IRC
# For "fun," a DRY metaprogrammed version
class Product
ATTRIBUTES = %i[name price]
ATTRIBUTES.each { |attribute| attr_reader attribute }
def initialize(**keywords)
missing = ATTRIBUTES - keywords.keys
if missing.any?
message = "missing keywords: #{missing}.map(&:inspect).join(', ')"
raise ArgumentError, message
end
ATTRIBUTES.each do |attribute|
keyword = keywords.fetch(attribute)
instance_variable_set :"@#{attribute}", keyword
end
end
def dig(key)
instance_variable_get(:"@#{key}") if ATTRIBUTES.include?(key.to_sym)
end
end
product = Product.new(name: 'scissors', price: 8)
array = [product]
array.dig(0, :name)
#=> "scissors"
class Product
attr_reader :name
attr_reader :price
def initialize(name:, price:)
@name = name
@price = price
end
def dig(key)
case key.to_sym
when :name
@name
when :price
@price
end
end
end
product = Product.new(name: 'scissors', price: 8)
array = [product]
array.dig(0, :name)
#=> "scissors"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment