'What does an argument with a colon but no default value do?

I've seen something like this a couple times with ruby/rails code:

def self.cool_function(a, b:, c:)
   ...
end

But I am having trouble figuring out what it means



Solution 1:[1]

It means it's a required (keyword) argument.

You can see this by trying to call the method without one of those arguments:

cool_function(1)
#=> ArgumentError: missing keywords: :b, :c

So to correctly call the function, you must include those keywords, e.g.:

cool_function(1, b: 2, c: 3)

There is lots of documentation and blog posts around this core language feature. For example, you may find this post helpful to dig into the topic in much more detail.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom Lord