Skip to content

Instantly share code, notes, and snippets.

@tamalw
Last active December 13, 2015 22:18
Show Gist options
  • Save tamalw/4983089 to your computer and use it in GitHub Desktop.
Save tamalw/4983089 to your computer and use it in GitHub Desktop.
str = "It's not too scary when you realize that everything is an object"
str.size # => 64
str.class # => String
str = "and you call methods on them"
str.reverse # => "meht no sdohtem llac uoy dna"
# EVERYTHING is an object
3.class # => Fixnum
nil.class # => NilClass
true.class # => TrueClass
/^regexps\stoo!$/.class # => Regexp
# EVERYTHING has methods
str.nil? # => false
[].empty? # => true
1 + 1 # => 2
1.+(1) # => 2
# Methods are chainable
str.upcase.reverse # => "MEHT NO SDOHTEM LLAC UOY DNA"
# Symbols aren't scary either, they are objects similar to strings
:foo.class # => Symbol
:foo.to_s # => "foo"
"foo".to_sym # => :foo
# But they are different, two identical strings will have different object ids, two identical symbols will have the same
"foo".object_id == "foo".object_id # => false
:foo.object_id == :foo.object_id # => true
# Symbols are handy for hash keys, among other things:
bar = { 'name' => "Tamal", 'status' => "Poopin'" }
bar['status'] # => "Poopin'"
baz = { :name => "Tamal", :status => "Poopin'" }
bar[:status] # => "Poopin'"
# Some methods allow you to iterate over the contents with blocks
ary = [1,2,3]
i = 0
while i < ary.size
puts ary[i]
i += 1
end
# >> 1
# >> 2
# >> 3
[1,2,3].each { |i| puts i }
# >> 1
# >> 2
# >> 3
# Some iterators let you modify the contents and return a new value
ary = [1,2,3]
new_ary = []
i = 0
while i < ary.size
new_ary << ary[i] * 100
i += 1
end
new_ary # => [100, 200, 300]
[1,2,3].map { |number| number * 100 } # => [100, 200, 300]
# Blocks can use curly braces or do..end
[1,2,3].map do |number|
number * 100
end # => [100, 200, 300]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment