Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'rubygems' # skip this line in Ruby 1.9
require 'sinatra'
get '/' do
"Hello, world!"
end
# These are method calls with 0 arguments. The former is considered best practice.
"345".to_i #convert that string to an integer!
"345".to_i()
# This one's a little tricky! Every object, even integers, are objects, and + is just a method.
4 + 5
4.+(5) # please don't do this one
# TWO arguments. And chaining. Now we're cookin'.
"Hello.".insert(5, " world")
"Hello.".insert 5, " world" # please don't do this
"Hello.".insert(5, " world").slice(0, 5)
# Iterating over an array using a block
[1, 2, 3].map do |el|
el + 1
end # result: [2, 3, 4]
# You can also do simple blocks like this:
[1, 2, 3].map {|el| el + 1}
[1, 2, 3].map() {|el| el + 1} # this is equivalent, but pointless
# {}-style blocks can be multiline too (as do; end; can be single-line) but most don't.
# Using a block and a method. Notice how even though the block is /after/ the ()s of the method, it's still passed in to the #inject method.
[1, 2, 3].inject(0) {|memo, val| memo + val} # yields 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment