Created
November 18, 2012 00:49
-
-
Save prasanthj/4102128 to your computer and use it in GitHub Desktop.
ruby snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*`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