-
2 weeks 2 days
-
2 weeks 4 days
-
4 weeks 2 days
-
4 weeks 5 days
-
4 weeks 6 days
Ruby's spaceship operator
When I first saw this operator I thought this is not something that I'll be using more often, but it turns out that this thing is really handy. To illustrate this, I have a simple string sorting according to its length:
def sort_by_len(list = [])
unless list.size == 0
list.sort! do |s1,s2|
s1.length <=> s2.length
end
else
false
end
end
fruits = ['Apple', 'Banana', 'Mango', 'Plum']
sort_by_len(fruits)
puts fruits
Now I know there are several ways on how to do this but I actually think this looks elegant. The way the operator works is it compares the length. If s1 is less than s2, it returns -1. if they're equal it returns 0 and if s1 is greater than s2 it returns 1. cool huh!

Facebook
Twitter
Post new comment