this post was submitted on 22 Nov 2023
294 points (100.0% liked)

196

16293 readers
37 users here now

Be sure to follow the rule before you head out.

Rule: You must post before you leave.

^other^ ^rules^

founded 1 year ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] Synthead@lemmy.world 14 points 10 months ago (2 children)

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.

[–] CoderKat@lemm.ee 19 points 10 months ago (3 children)

In Ruby, 0 and "" is truthy,

What the fuck?

[–] diemartin@sh.itjust.works 8 points 10 months ago

Lua is the same. Only false and nil are "falsey".

I remember I fixed a bug in a mod for Minetest that assumed 0 was false and caused an infinite loop.

[–] Synthead@lemmy.world 4 points 10 months ago* (last edited 10 months ago) (1 children)

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)
[–] DarkenLM@kbin.social 4 points 10 months ago

And people bash Javascript as if it was the devil when thinks like this exist on other languages.

[–] calcopiritus@lemmy.world 2 points 10 months ago

Python also has about 9000 alternatives that are better than this.

Allowing anything other than variables, number literals, and ':' inside list indices was a mistake.