41
"Useless syntax sugar": Numbered block parameters in Ruby
(zverok.space)
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Follow the wormhole through a path of communities !webdev@programming.dev
It wouldn't be as relevant, since passing a function or method instead of a closure is much easier in Rust - you can just name it, while Ruby requires you to use the
methodmethod.So instead of
.map(|res| res.unwrap())you can do.map(Result::unwrap)and it'll Just Work™.Except when Type::Method takes a reference, then it doesn't just work
Well, that's to be expected - the implementation of
mapexpects a function that takes ownership of its inputs, so you get a type mismatch.If you really want to golf things, you can tack your own
map_ref(and friends) onto theIteratortrait. It's not very useful - the output can't reference the input - but it's possible!I imagine you could possibly extend this to a combinator that returns a tuple of
(Input, ref_map'd output)to get around that limitation, although I can't think of any cases where that would actually be useful.In the case of your example we'd do
.map(&:unwrap)in Ruby (if unwrap was a method we'd actually want to call)Notably, these are not the cases
_1and_2etc are for. They are there for the cases that are not structurally "call this method on the single argument to the block" e.g..map{ _1 + _2 }or.map { x.foo(_1) }(
_1is reasonable, because iterating over an enumerable sequence makes it obvious what it is;_1and_2combined is often reasonable, because e.g. if we iterate over a key, value enumerable, such as what you get from enumerating aHash, it's obvious what you get; if you find yourself using_3or above, you're turning to the dark side and should rethink your entire life)