Human-readable listing of array elements

On 10.12.2009 18:48, Aldric G. wrote:

That point is not exactly true: while it doesn’t out of the box…
nah
=> 5
irb(main):003:0>

Alright… Well then, I’m confused.

My comment referred to the “won’t handle <=” part. I demonstrated how
it can be made to handle less than comparisons directly, i.e. without
using ranges which is not exactly the same operation.

Cheers

robert

Shot (Piotr S.) wrote:

Aldric G.:

This took me less than a minute to write, but I don’t know if it’s as
elegant as it could be. Are there more “Ruby-like ways™” to write
this?

    string += ", #{element}"
end

end
string
end

Couldn’t resist:

def stringify a
a.size < 2 ? a.first.to_s : a[0…-2].join(', ') + " and #{a.last}"
end

stringify []
=> “”
stringify [‘Arthur’]
=> “Arthur”
stringify [‘Arthur’, ‘Ford’]
=> “Arthur and Ford”
stringify [‘Arthur’, ‘Ford’, ‘Trillian’]
=> “Arthur, Ford and Trillian”
stringify [‘Arthur’, ‘Ford’, ‘Trillian’, ‘Marvin’]
=> “Arthur, Ford, Trillian and Marvin”

— Shot

I like it!

Best,
–Â
Marnen Laibow-Koser
http://www.marnen.org
[email protected]