Skip to content

Instantly share code, notes, and snippets.

View yangsu's full-sized avatar

Yang Su yangsu

  • San Francisco, CA
  • X @ys65
View GitHub Profile
@yangsu
yangsu / ruby-typing.rb
Created January 28, 2013 03:32
Ruby Typing
4 + 4 # g8
4 + "foo" # results in a TypeError, hence strongly typed
4 + 4.0 # => 8.0 this works because of type coercion
# What about this though?
def add_stuff
4 + "foo"
end # => nil
add_stuff # => TypeError This proves that Ruby is dynamically typed
@yangsu
yangsu / ruby-duck-typing.rb
Created January 28, 2013 03:37
Ruby Duck Typing
i = 0
a = ['100', 100.0, '50', 50.0]
while i < a.size
<b>puts a[i].to_i</b>
i = i + 1
end
@yangsu
yangsu / ruby-vars.rb
Created January 28, 2013 03:37
Ruby Variables
foo = 'hello, plcourse' # here we define a function. Notice there's no type declaration
foo = 'is mutable' # variables are mutable, i.e. they can vary
CONSTANTS = 'are defined like this' # they are immutable
@yangsu
yangsu / ruby-func-call.rb
Created January 28, 2013 03:38
Ruby Function Call
puts(foo) # this prints "hello, plcourse" and returns nil
puts foo # this is exactly the same as above, with a bit of syntactic sugar
@yangsu
yangsu / ruby-func-declaration.rb
Created January 28, 2013 03:39
Ruby Function Declaration
def be_truthful
42
true # The last expression is always the one that gets returned
end
@yangsu
yangsu / ruby-precedence.rb
Last active December 11, 2015 20:08
Ruby Precedence Nuance
foo = false or true # This expression evaluates to true
# => true
foo # But it assigned foo to false
# => false
@yangsu
yangsu / ruby-arrays.rb
Created January 28, 2013 03:41
Ruby Arrays
[1, "two", 3] # is perfectly valid
Array.new # remember, these are objects, and objects can be instantiated
# with .new()
cars = ['ford', 'toyota', 'subaru']
cars[0] # => "ford"
cars[2] # => "subaru"
cars[-1] # => "subaru"
cars[-4] # => nil
cars[9001] # => nil
@yangsu
yangsu / ruby-hashes.rb
Created January 28, 2013 03:42
Ruby Hashes
# Literal Form
numbers = { 1 => 'one', 2 => 'two' }
# => {1=>"one", 2=>"two"}
# Accessing element using key
numbers[1] # => "one"
# Can use symbols as keys
stuff = { :array => [1, 2, 3], :string => 'Hello' }
# => {:array=>[1, 2, 3], :string=>"Hello"}
@yangsu
yangsu / ruby-named-param.rb
Created January 28, 2013 03:43
Ruby Named Parameters
def tell_the_truth(options={})
if options[:profession] == :lawyer
'it could be believed that this is almost certainly not false.'
else
true
end
end
tell_the_truth
# => true
@yangsu
yangsu / ruby-yielding.rb
Created January 28, 2013 03:43
Ruby Yielding
class Fixnum
def my_times
i = self
while i > 0
i -= 1
yield
end
end
end