Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
@pk76 the `*` is called the splat operator; and yes, it will do what you were after.
If you want readability, though just make the first line of your method `args = Array.wrap(args)` and kill off the splat. -
Not sure if sarcasm, but yes, helper methods exist for these cases.
I miss the strong types from my C# days. It makes the code so much more predictable. But I can't deny that dynamic typing has some nice benefits as well - it's just a different coding mindset. -
Root824527yYep. One character: the * splat operator.
Or array wrapping as @fattymiller pointed out.
Or:
x = [x] unless x.is_a? Array -
pk7611727y@fattymiller @Ashkin This all seems like way too many options to do what the compiler would do for me with strong typing.
Only reason I did it at all was the asshole client sprung it on me last moment. I promise they regret that move. -
@pk76 wouldn't strong typing have errored if used like that from the console, though? Passing a single `string` versus a `string[]`?
Even in C# you would use the splat operator to mean "zero or more parameters" -
pk7611727y@fattymiller In Ada and C#, which are my most commonly used languages, the command line args are always an array, and all of the functions in this script would also return arrays, so no this problem would have never happened, you'd just get single element arrays.
Related Rants
Why I don't use Stack Overflow 99% of the time:
Me: I'm not a ruby developer, but I have to write a small script in ruby. I ran into a problem where i'm getting behavior I don't expect. I have a method which expects an array, and when multiple items are passed into it from the command line parser, behaves appropriately, but when only one command line argument is passed, the method breaks because it was passed a single element, not an array of one element. Here's my code, how do I get my desired behavior?
Most highly voted answer: your problem is your passing it a single element and not an array
Question downvoted into oblivion. As if i'm a pleb for not immediately having a perfect grasp of dynamic typing because when I have the choice I stick with strong nominative typing.
undefined
stack overflow
did you even read the question