• 0 Posts
  • 19 Comments
Joined 1 year ago
cake
Cake day: June 28th, 2023

help-circle





  • Synthead@lemmy.worldto196@lemmy.blahaj.zonedoes this code run rule
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    1 year ago

    Yup :) Everything in Ruby inherits Object, too. It’s a really neat language, and when you get accustomed to it, you might wonder why some other languages aren’t written like it.

    For the 0 value being truthy, consider that Ruby is a dynamic language. Imagine if you asked a user how many motorcycles they own. If they answer, you’ll have an Integer. If they don’t, you’ll have nil, from NilClass. 0 is just as valid of an answer as 2, so you can do something like this:

    raise NoResponse unless motorcycles
    
    save_motorcycles(motorcycles)
    

  • Ruby has a method for this :)

    [1] pry(main)> vars = ["one", "two", nil, "three"]
    => ["one", "two", nil, "three"]
    [2] pry(main)> vars.compact
    => ["one", "two", "three"]
    

    In Ruby, 0 and "" is truthy, so this would be a little different than the Python interpretation. You could filter with #select, but you’d typically write your code around this instead.