open("file", "r").readlines.
map{|line| line.strip}.
filter{|line| line != ""}
or some smarter but less readable ways.I prefer the left-to-right transformations style to Python's list comprehension and inside-to-outside function composition. The reason is that it reminds me of how data flow into *nix pipelines. I spent decades working with them and I've been working with Ruby for the last half of that time. With Python in the last quarter of my career.
It's a matter of choices and preferences of the original designed of the language. Both ways work.
filter(None, xs)
is equivalent to: filter(lambda x: x, xs)
That is, it will return an iterator over the truthy elements of the passed iterable.Certainly, I agree; I would usually use:
(x for x in xs if x)
Or, if I know more about the kind of falsy values xs actually needs removed, something more explicit like: (x for x in xs if x is not None)
Because Python’s multiplicity of falsy values can also be something of a footgun (particularly, when dealing with something a collection of Optionals where the substantive type has a falsy value like 0 or [] included.)Instead of:
filter(None, xs)
Which is terse but potentially opaque.Though it's additional syntax, I kind of wish genexp/list/set comprehensions could use something like “x from” as shorthand for “x for x in”, which would be particularly nice for filtering comprehensions.
If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
So it just removes false-y values.
Very handy I've used it a ton