Skip to content

Instantly share code, notes, and snippets.

@bradkrane
Last active Apr 16, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@bradkrane bradkrane commented Apr 13, 2021

James Brocklebank OG code.

@bradkrane

This comment has been minimized.

Copy link
Owner Author

@bradkrane bradkrane commented Apr 14, 2021

Definitely missing much here, I'm sure but it must wait for later to be sorted

@bradkrane

This comment has been minimized.

Copy link
Owner Author

@bradkrane bradkrane commented Apr 16, 2021

Sorted out the issues.

@bradkrane

This comment has been minimized.

Copy link
Owner Author

@bradkrane bradkrane commented Apr 16, 2021

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