Skip to content

Instantly share code, notes, and snippets.

@zh
Created December 10, 2011 03:00
Show Gist options
  • Select an option

  • Save zh/1454418 to your computer and use it in GitHub Desktop.

Select an option

Save zh/1454418 to your computer and use it in GitHub Desktop.
Some good Ruby syntax examples
w = %w[a c d b e]
w.sort #=> ["a", "b", "c", "d", "e"]
w.sort.reverse #=> ["e", "d", "c", "b", "a"]
w.sort { |a,b| b<=>a } #=> ["e", "d", "c", "b", "a"]
w.reduce(&:+) #=> "acdbe"
w.map(&:upcase) #=> ["A", "C", "D", "B", "E"]
w.include? "a" #=> true
w.member? "a" #=> true
(1..8).select { |x| x % 2 == 0 } #=> [2, 4, 6, 8]
(1..8).reject { |x| x % 2 == 0 } #=> [1, 3, 5, 7]
langs = %w[ruby python perl]
langs.group_by { |lang| lang[0] } #=> {"r"=>["ruby"], "p"=>["python", "perl"]}
langs.map { |lang| lang.capitalize } #=> ["Ruby", "Python", "Perl"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment