Skip to content

Instantly share code, notes, and snippets.

@prasanthj
Created November 18, 2012 00:49
Show Gist options
  • Save prasanthj/4102128 to your computer and use it in GitHub Desktop.
Save prasanthj/4102128 to your computer and use it in GitHub Desktop.
ruby snippets
*`which` in ruby*
http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
def which(cmd)
exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
exts.each { |ext|
exe = "#{path}/#{cmd}#{ext}"
return exe if File.executable? exe
}
end
return nil
end
*sort descending hash based on value*
a = {"earn"=>2, "acq"=>11, "trade"=>3}
1) a.sort_by{|k,v| -v}
2) Hash[*a.sort{|a,b| b[1]<=>a[1]}.flatten]
*check if a string is number*
http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails
class String
def is_number?
true if Float(self) rescue false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment