Created
November 16, 2015 04:03
-
-
Save trishume/426497905adab9074f7c to your computer and use it in GitHub Desktop.
Ruby is awesome
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
def ruby_is_great | |
# times is an ordinary method that acts just like a loop | |
# it takes a block, which is like a lambda/anonymous function | |
# except it acts like you would expect a control structure to | |
5.times do |i| | |
# this will return from ruby_is_great not the block | |
return if rand() < 0.5 | |
puts i | |
end | |
end | |
# This function takes a block and runs it twice with argument 5 | |
def twice(&block) | |
block.call(5) | |
block.call(5) | |
end | |
# There is a handy form that looks like this | |
def twice_2 | |
yield 5 | |
yield 5 | |
end | |
# when you use this block, control structures like "break" | |
# do what they should | |
twice do |z| | |
puts z # will print 5 | |
break # will stop the block from running any more times | |
end | |
class Bob | |
# Automatically creates getter and setter methods for you that you can override later | |
attr_accessor :lol | |
def initialize | |
@lol = 4 # handy short form instance variables, no "this." | |
4.times do | |
@lol += 1 # actually works, no weird "this" tricks like JS | |
end | |
end | |
end | |
b = Bob.new | |
# setter and getters look exactly like fields when used | |
puts b.lol | |
b.lol = 2 | |
# Ruby has a great immensely powerful standard library and all sorts of handy things | |
# you don't have to know them or use them when you are learning, but they are great | |
# when you become pro. | |
# Finds most common starting letter in English | |
File.open('/usr/share/dict/words','r').map(&:downcase) | |
.chunk(&:ord).map {|c, l| [c.chr, l.length]} | |
.max_by(&:last) # => ["s", 25162] | |
# I did a presentation on how cool the standard library is: http://thume.ca/2014/06/25/a-tour-of-the-ruby-standard-library/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment