14
pk76
7y

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.

Comments
  • 8
    Remember, kids:
    Rubies are made of carbon,
    but so is shit.
  • 1
    @jschmold Yeah I got it working. Something having to do with * making it an array regardless. Not an intuitive to read language.
  • 2
    @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.
  • 0
    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.
  • 0
    Yep. One character: the * splat operator.

    Or array wrapping as @fattymiller pointed out.
    Or:
    x = [x] unless x.is_a? Array
  • 0
    @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.
  • 0
    @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"
  • 1
    @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.
Add Comment