Last active
April 16, 2021 18:50
-
-
Save bradkrane/e051d205024a5313cb4a5b9eb1eae0e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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) |
Definitely missing much here, I'm sure but it must wait for later to be sorted
Sorted out the issues.
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
James Brocklebank OG code.