Skip to content

Instantly share code, notes, and snippets.

@bradkrane
Last active April 16, 2021 18:50
Show Gist options
  • Save bradkrane/e051d205024a5313cb4a5b9eb1eae0e3 to your computer and use it in GitHub Desktop.
Save bradkrane/e051d205024a5313cb4a5b9eb1eae0e3 to your computer and use it in GitHub Desktop.
module Kernel
def to_hash
new_hash = self.instance_variables.reduce({}) do |hash, instance_var|
hash[instance_var.to_s[1..-1].to_sym] = self.instance_variable_get instance_var
hash
end
end
end
# Then you can pass it a list of symbols.
# Then for your method:
def some_method name:, weight:
puts "#{name} weighs #{weight}"
end
class Dog
attr_reader :name, :weight
def initialize name:,weight:
@name = name
@weight = weight
end
end
a_dog = Dog.new name: 'fido', weight: '7kg'
some_method(**a_dog) # Works great!
class CockerSpanel < Dog
def initialize name:,weight:,color:
super name: name, weight: weight
@color = color
end
end
another_dog = CockerSpanel.new name: 'Jessie', weight: '5kg', color: 'black'
some_method **another_dog
exit # the below works.
# It's not perfect but it's pretty close.
# Should def be a native implementation though.
# Basically ** is used for named arguments (where you pass a hash).
def x(name:, age:)
puts "#{name} #{age}"
end
attributes = {name: 'Test', age: 55}
x(**attributes)
@bradkrane
Copy link
Author

Sorted out the issues.

@bradkrane
Copy link
Author

Fixed an issue with hash/object passing to other_splat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment