3 ms·
> I've grown fairly fond of JS implicitly named object parameters, and I always liked Smalltalk's named(-ish) parameters, and this seems like an interesting com
by mhink 5y ago
> I've grown fairly fond of JS implicitly named object parameters, and I always liked Smalltalk's named(-ish) parameters, and this seems like an interesting compromise. I'm not actually sure how Ruby works in this case? I thought its parameters were fairly normal. Are there other languages that do this?
Ruby allows keyword arguments, which are very similar to object parameters in Javascript:
# ruby
def add(a, b, *args, x:, y:, **kwargs)
puts a.to_s
puts b.to_s
puts args.to_s
puts x.to_s
puts y.to_s
puts kwargs.to_s
end
add(1, 2, 3, 4, y: 'bar', x: 'foo', z: 'quux')
# => 1
# => 2
# => [3, 4]
# => foo
# => bar
# => {:z => 'quux'}
there are also 'splats', which are pretty much the same as array/object spreading in JS:
# ruby
positional_args = [1,2,3,4]
keyword_args = { :x => 'foo', :y => 'bar', :z => 'quux' }
add(*positional_args, **keyword_args)
# => (same output as previous example)
One thing that's missing in Ruby (that I quite like in JS) is the ability to rename keyword arguments in the named parameter list, like:
// javascript
const example = ({ max: maxNum = 123 }) => {
/* ... */
};
# ruby
def example(max: 123)
max_num = max # can't do this in the parameter list
# ...
end
Honestly, this limitation is just about the only thing I think is missing from Ruby's parameter-list syntax.
> But in the case of one-parameter functions this seems unnecessary, the function name often makes it clear exactly what the first parameter is. And if you are going to support Subject-Verb-Object phrasing (as suggested later) then the Subject is another implicit parameter that probably doesn't need naming.
Maybe there could be a special sigil for positional arguments? I like the idea of gently discouraging them, but still making them possible. Maybe something like
// hypothetical language
function singleArgFunction(@arg0: number) { /* ... */ }
function mixedArgFunction(@arg0: number, foo: string, bar: string) { /* ... */ }
function standardFunction(alfa: number, bravo: string) {/* ... */}
singleArgFunction(0);
mixedArgFunction(1, foo: 'hello', bar: 'world');
standardFunction(alfa: 123, bravo: 'abc');
- KarlKemp 5y agoruby 3.1 added the feature OP is quoting. If you have local variables x and y and the method definition def doit(:x, :y) you can just call it with, IIRC: doit(x:, y:) instead of doit(x: x, y: y) as was needed before.