Recently I have been dreaming and talking a lot about methods. Here are few cool things which I discovered on my way to get better at Ruby. I’ll talk about different ways in which we can pass parameters to a method. Continue to find out how many of them did you knew already. You can read my difference between class methods and instance methods for some more fun.
The common method
def full_name(first, last)
"#{first} #{last}"
end
full_name('sam', 'smith')
=> "sam smith"
Named parameters
def parse(name: 'Jhon', hero: 'superman')
"I am #{name}, the #{hero}"
end
parse
=> "I am Jhon, the superman"
parse(name: 'Harry Potter', hero: 'wizard')
=> "I am Harry Potter, the wizard"
parse(name: 'Luffy', food: 'meat')
# ArgumentError: unknown keyword: food
Any number of unnamed parameters
def attributes(*args)
args.join(', ')
end
attributes('hi', 'how', 'are', 'you')
=> "hi, how, are, you"
Any number of named parameters
def fields(args = {})
args.each do |k,v|
puts k, v
end
end
fields(name: 'adf', fasd: 'fasd')
name
adf
fasd
fasd
=> {:name=>"adf", :fasd=>"fasd"}
Conclusion
We can do mix and match of all these different ways of sending params and create a very robust method. I hope you find this helpful. If I missed somthing do let me know in the comments below. Thanks for reading.