Reputation: 2803
I often prefer to do this:
a, b = lambda do |data|
[f1(data), f2(data)]
end.call(some_function(some_data))
instead of this:
data = some_function(some_data))
a, b = f1(data), f2(data)
or this:
a, b = f1(some_function(some_data)), f2(some_function(some_data))
Is there any negative consequence from using lambdas for almost every single thing?
Upvotes: 1
Views: 455
Reputation: 11395
The principal consequence is Ruby programmers aren't particularly accustomed to doing it this way. Either one of your alternatives would be more easily readable by members of the community, other members of your team, future maintainers, etc.
The secondary consequence is creating one-off lambda functions in this way will be slower than calling static functions. Creating lambdas aren't extraordinarily slow by any means, but it's still slower than not using them. If you did this a lot, it would start to add up. To give some context, creating an empty lambda takes about 10 times longer to create than an empty array. So if you were doing this repeatedly (e.g. inside a function call that gets used over and over), that difference could add up.
Lastly, there is at least one other way to do it. I'm sure some others exist, too...
a, b = [:f1, :f2].collect { |fn| send(fn, some_function(some_data)) }
All in all, though, I think your first alternative is the cleanest approach:
data = some_function(some_data)
a, b = f1(data), f2(data)
It's entirely clear what you're doing and is also efficient.
Upvotes: 6
Reputation:
I can't comment yet so I'm just going to mirror Wuputah, he's right. Every single Ruby optimization video I've watched and every book I've read has said to avoid lambdas unless you absolutely need them because they can be huge performance hits when you try to scale your app. This isn't to say you shouldn't use them, just don't abuse them.
Upvotes: 3