Article on the previous symbol
As I mentioned in my last article on symbols, symbols are a better choice for hash keys than strings. If you use a symbol for the hash key, you get the following code.
menu = { :food => 'rice', :dessert => 'cake'}
#When retrieving a value
menu[:dessert] # => "cake"
#When adding a new key / value combination
menu[:drink] = 'water'
p menu # => {:food=>"rice", :dessert=>"cake", :drink=>"water"}
If the symbol is the key, you can create the hash with the notation symbol: value
without using =>.
(* The position of the colon changes from left to right)
(Example)
menu = {food: 'rice', dessert: 'cake'}
#Same when fetching values
menu[:dessert] # => "cake"
(Example) Code when both key and value are symbols
{food: :rice, dessert: :cake, drink: :water}
When passing arguments to a method, use the method's keyword arguments to improve readability. The keyword arguments for the method are defined as follows:
def method name(Keyword argument 1:Default value 1,Keyword argument 2:Default value 2)
#Method implementation
end
(Example using keyword arguments)
def buy_food(menu, drink: true, dessert: true)
#Buy food
if drink
#Buy a drink
end
if dessert
#Buy dessert
end
end
#Buy rice, drinks and desserts
buy_food('rice', drink: true, dessert: true)
#Buy pizza and drinks
buy_food('pizza', drink: true, dessert: false)
When calling a method with keyword arguments, just as you did when you created the hash Symbol: Specify the argument in the form of a value.
In addition, the keyword argument has a default value, so you can omit the argument.
buy_food('rice', drink: true, dessert: true)
⬇︎ drink and dessert also use the default value of true, so do not specify them.
buy_food('rice')
You can omit the default value of the keyword argument.
def buy_food(menu, drink:, dessert:)
#abridgement
end
Keyword arguments that do not have default values cannot be omitted during the call. (If omitted, an error will occur.)
buy_food('rice', drink: true, dessert: true)
When calling a method that uses keyword arguments It is also possible to pass a hash (key is a symbol) that matches the keyword argument as an argument.
Params = { drink: true, dessert: false }
buy_food('rice', params)
Introduction to Ruby for those who want to become a professional
Recommended Posts