Recent comments


Syndicate


Follow Me

Twitter Facebook

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!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.