12341_2341_2_3_4123.41234.1234.0'Windows files can\'t get enough of \r\n'"Windows files can't get enough of \\r\\n""One line\nTwo line\nRed line\nBlue line""1 + 1 = #{1 + 1}""1 + 1 = 2"
<<XXX
<html>
\t<!-- HTML document here -->
</html>
XXX
"<html>\n\t<!-- HTML document here -->\n</html>\n"["The Answer", 42, ["Another dimension", 93.2]]some_hash[key] → value
{"The Question" => "What is six times four?", 1 => "one", [8,8] => "Chess" }[[8,8]] → "Chess"/bb|[^b]{2}//echo*/
"echoecho""echooooo"1..4is inclusive (includes 1, 2, 3, and 4)1...5 is an equivalent exclusive range (5 is not included)nil stands for 'nothing'true and false:symbols represent an identity, and are immutable| Addition | 1 + 1 → 2 |
| Subtraction | 4 - 3 → 1 |
| Multiplication | 7 * 2 → 14 |
| Integer Division | 18 / 4 → 4 |
| Real Division | 18 / 4.0 → 4.5 |
| Exponentiation | 3**4 → 81 |
3**64 → 3433683820292512484657849089281| Not | ~0 → -1 |
| And | 3 & 2 → 2 |
| Or | 5 | 3 → 7 |
| Xor | 3 ^ 1 → 2 |
| Left Shift | 3 << 2 → 12 |
| (Logical) Right Shift | 9 >> 2 → 2 |
-9 >> 2 → -3| And | true && false → false |
| And (alternate) | true and false → false |
| Or | true || false → true |
| Or (alternate) | true or false → true |
| Not | !false → true |
| Not (alternate) | not false → true |
| Exclusive Or | true ^ false → true |
false and nil0 is true!! to make something a boolean| Equals | 1 == 2 → false |
| Not equals | 1 != 2 → true |
| Less than | 1 < 2 → true |
| Less than or equal to | 2 <= 2 → true |
| Greater than | 1 > 2 → false |
| Greater than or equal to | 2 >= 2 → true |
| Cmp, aka "Spaceship" | 1 <=> 2 → -1 |
<=> returns a value less than, equal to, or greater than 0 if the same comparison holds for the left side to the right side. It returns nil if the comparison "doesn't make sense" (e.g. 1 < "hi" → nil| Concatenation | "Hello" + " World" → "Hello World" |
| Repetition | "Echo " * 3 → "Echo Echo Echo " |
| Pattern Matching (Success) | "Foobar" =~ /ob?a/ → 2 |
| Pattern Matching (Failure) | "Foobar" =~ /z+/ → nil |
| Formatting (sprintf) | "Line %04d" % 217 → "Line 0217" |
| Formatting, Multiple Values | "Result %03d: %f" % [19, 85.2] → "Result 019: 85.200000" |
| Indexing (Fetch) | [1,2,3][0] → 1 |
| Reverse Indexing | [1,2,3][-1] → 3 |
| Concatenation | [1,2] + [3,4] → [1,2,3,4] |
| Repetition | [1,2,3] * 2 → [1,2,3,1,2,3] |
| Append | [1,2] << 3 → [1,2,3] |
| Set Difference | [1,2,3] - [1,3,4] → [2] |
| Set Union | [1,2] | [2,3] → [1,2,3] |
| Set Intersection | [1,2] & [2,3] → [2] |
| Slicing | [1,2,3,4,5][1,3] → [2,3,4] |
| ... Negative Lengths? | [1,2,3][2,-1] → nil |
Capitalized 'words' are constantsthis and that could be local variable names$frequency is a global variableself is special; it refers to the current object ('this' in many languages)@mine is an object variable@@mine is a class variable variable. It is shared by all objects of that class (including its subclasses)a = b performs assignmenta = [1,2,3]
b = a
a << 4
b
→ [1,2,3,4]
a += b is semantically equivalent to a = a + b+= operator++ or --if score < 50
"That stinks"
elsif score < 70
"It needs more work"
else
"It's okie dokie pokie"
end
"Things have gone pear-shaped" if 2 < 1"City of Townsville needs you!" unless safegot_ruby ? "Mmm" : "Eww"case mystery
when "bob"
"Hi bob!"
when /\w+/
"Looks like a word ..."
when Numeric
"A number of some sort ..."
else
"I don't know"
end
===while presenting
pants_on = true
slide_number += 1
end
until comfortable
salary += 1
end
salary -= 1 while unsatisfactorywidgets *= 2 until enoughdef hello
"Hello World!"
end
return can be used to make a method return early (with a value if you like)hello takes no argumentshello → "Hello World!"hello() → "Hello World!"
def greet(name = "sir or madam")
"Good day #{name}"
end
greet takes one argument, and it's optionalgreet → "Good day sir or madam"greet "Bob" → "Good day Bob"? or !
? for methods that ask questions, like [1,2].include? 'a'! when there are two versions of a method: one that that modifies the original and one that doesn't. Array#sort returns a new array that's sorted, while Array#sort! sorts an array in-place (and returns that same array)def greet_many(*names)
"Good day #{names.join(' and ')}"
end
greet_many takes no, one, or many argumentsgreet_many → "Good day "greet_many "Linda" → "Good day Linda"greet_many "Flopsy", "Mopsy" → "Good day Flopsy and Mopsy"def make_captcha(name, options = {})
width = options[:width] || 200
width = options[:height] || 80
# more code ...
end
make_captcha takes one argument and some (optional) named argumentsmake_captcha "captcha1"make_captcha "captcha2", :width => 100if), punctuators (e.g. ','), and objects"one, two, three".split(/,\s*/) → ["one","two","three"](5.3).round → 5"hi"*3 → "hihihi"3*"hi" ! TypeErrore = "Something"
["hi",98,:bar].each do |e|
puts e
end
retry causes the block to run again with the same argumentsnext ends this run of the blockbreak ends this run and the method calling the blockdef attend_sessions(*sessions)
i = 0
sessions.each do |s|
puts "Attending session #{i}: #{s}"
yield s
end
end
def attend_sessions(*sessions, &block)
# same code
block.call s
# same code
end
class BarCamp
DEFAULT_FUN = 10**6
def initialize
@fun = DEFAULT_FUN
end
def bored_attendees(num)
@fun = DEFAULT_FUN - 100*num
end
def is_boring?
@fun < 1000
end
end
event = BarCamp.new
event.bored_attendees 10
event.is_boring?
|
|
begin
1/0
rescue Exception => e
puts "Caught Exception!"
puts e
finally
puts "This is always printed"
end
throw obj will throw any object as an exceptionraise MyExceptionClass, arg, backtrace will create and throw a MyException with arg and print backtrace instead of the actual trace. all arguments are optionalraise with no arguments within a rescue block will re-raise the exception that was caughtinclude other modulesclass Lame
include Comparable
def <=>(o)
3 <=> o
end
end
<=>module CrookedVein
include Comparable
BUDGET = 500_000_000
def self.publish
puts "Here's a book"
end
def investigate
# do stuff
end
end
CrookedVein::BUDGET → 500000000CrookedVein.publish prints "Here's a book"include CrookedVein, then it's instances will have an investigate methodincludes CrookedVein, then it also acquires comparison operators (from Comparable)AClass.ancestors will show you the order1.class.ancestors → [Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel]ObjectObject that can hold methods for instances and act as a namespaceObject has a class (some_obj.class). Modules are instances of Module and classes are instances of Class"".is_a? Object → trueFixnum < Numeric → trueclass Address
# getter
def number
@number
end
# setter
def number=(n)
@number = n
end
attr_accessor :street, :city, :state
end
attr_accessor makes setters and getters for youclass Barker
def self.sayer(meth_name)
define_method meth_name do
puts "#{meth_name}!!"
end
end
sayer :hey
sayer :stop!
end
b = Barker.new
b.hey
b.stop
self has been used a lot to add methodsself is an Object but objects can't have methodsClass that the methods are added toself.sayer wasn't a method in the Class itself, but in it's metaclasso = Object.new
def o.works
"This works"
end
class << o
MY_CONST = 3
def also
"This works too, and gives more access"
end
# no access to outside variables :(
end
some_var = 2
(Foo = Module.new).module_eval do
define_method "Some#{some_var}" do
"This is Some#{some_var}"
end
end
class Foo < some_method() is validclass Bar < Module is validmethod_added and method_missing)