def find_document title, author
#...
end
find_document 'Frankenstein', 'Shelley' puts "hello world" "my lord!".instance_of? Stringif words.size < 100enddef words @content.split end
def find_document(title, author)
enda.b(c).d(e).fthing.should_receive(:some_method).once.with
def try(*args) puts args; end try 1,2 => 1 2def try *args puts args; endtry 1, 2, 4 SyntaxError: (irb):15: syntax error, unexpected tIDENTIFIER, expecting ';' or '\n' def try *args puts args; end; ^ (irb):15: syntax error, unexpected keyword_end, expecting end-of-input def try *args puts args; end;
task :rake => pre_rake_task do something end #really means: task(:rake => pre_rake_task){ something }#but task :rake => pre_rake_task { something } #really means: task :rake => (pre_rake_task { something })#solution - brackets task(:rake => pre_rake_task) { something }
def method_to_be_overriden; puts 'I override you!'; endclass DocumentException < Exception; end
*don't cram too much into 1 line!
10.times { |n| puts "The number is #{n}" }
Rule 1:
single statement => braces
more statements => do..end
Rule 2:
blocks that return values => braces
blocks that are executed for side effects => do..end
# block used only for side effectlist.each do |item| puts item end # Block used to return test value list.find { |item| item > 10 } # Block value used to build new value list.collect { |item| "-r" + item }
Gotcha!
puts [1,2,3].map{ |k| k+1 } 2 3 4 => nilputs [1,2,3].map do |k| k+1; end #<Enumerator:0x000000009f9a20> <0x0000010a06d140 style="font-style: normal; font-variant: normal;">=> nil#same as [1,2,3].map() do |k| k+1; end
f g { }
#is parsed as f(g { })
f g do end
#is parsed as f(g) do end [].empty? => true
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten! => [1, 2, 3, 4, 5]
a => [1, 2, 3, 4, 5] #bad codedoc.words.each { |word| some_really_really_long_expression( ... with lots of args ... ) }
pi = Float('3.14159') #float is a method! #turnif !@read_only #into unless @read_only#this is executed if "@read_only == false/nil"
#turn
while ! document.is_printed?
...
end
#into
until document.printed?
...
end #don't use unless with negations and multiple conditions
unless !person.present? && !company.present?
end
#do
if person.present? && company.present?
end #don't use with else
unless person.present?
puts "Not present"
else
puts "Present"
end
#do
if person.present?
puts "Present"
else
puts "Not present"
end @title = new_title unless @read_onlydocument.print_next_page while document.pages_available?
fonts = [ 'courier', 'times roman', 'helvetica' ]for font in fonts puts font end fonts.each do |font| puts font end
numbers = [1,2,3]numbers.each {|i| zmienna = i; } zmienna => NameError: undefined local variable or method `zmienna' for main:Objectfor i in numbers zmienna = i end zmienna => 3
case title when 'War And Peace' puts 'Tolstoy' when 'Romeo And Juliet' puts 'Shakespeare' elseputs "Don't know"end
#which can be compacted to
author = case title
when 'War And Peace' then 'Tolstoy'
when 'Romeo And Juliet' then 'Shakespeare'
else "Don't know"
end
Fixnum === 2 #=> true
Fixnum.ancestors => [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]
Integer === 2 #=> true (1...10) === 5 => true /AB/i === 'ab' => true
2 === Fixnum #=> false
case title when /War And .*/ puts 'Maybe Tolstoy?' when /Romeo And .*/ puts 'Maybe Shakespeare?'end
case doc when Document puts "It's a document!" when String puts "It's a string!"end
# Broken in a subtle way...
while next_object = get_next_object
# Do something with the object
end
until (next_object = get_next_object).nil?
# Do something with the object
end ret = if @not_before && @not_before > time [false, :expired, "not valid before '#@not_before'"] elsif @not_after && @not_after < time [false, :expired, "not valid after '#@not_after'"]end
*Don’t try to use ||= to initialize things to booleans - use memoist gem instead@first_name = '' unless @first_name#or@first_name ||= ''#which is not the same as "@first_name = @first_name || ''"
file = all ? 'specs' : 'latest_specs' book_info = { first_name: 'Russ', last_name: 'Olsen' } poem_words = %w{ twinkle little star how I wonder }
=> ["twinkle", "little", "star", "how", "I", "wonder"]
def load_font( name, size = 12 )
# Go font hunting...
end def echo_all( *args ) args.each { |arg| puts arg } end#so no instead ofecho_all ["he", "ll", "o"]#you can doecho_all "he", "ll", "o"
def some_method(string, *args, hash) my_array = [1,2,3]
#if some_method takes 3 parameters
some_method( *my_array ) load_font { :name => 'times roman', :size => 12 }array = [[key_1, value_1], [key_2, value_2], ... [key_n, value_n]]
Hash[*array.flatten]
#Hash[key1, value1, ...] = { key1 => value1, ... } first, second, *rest = [1,2,3,4,5]
first => 1
second => 2
rest => [3,4,5] movie = {a: 1, b: 2}movie.each { |key, value| puts "#{key} => #{value}"}a => 1 b => 2 => {:a=>1, :b=>2}
["aa", "a", "Aa"].find_index { |word| word.length == 2 && word =~ /aa/ }=> 0
require 'pp'pp ["aa", "a", "Aaa"].map { |word| word.size } =>[2, 1, 3]
words = ["amber", "bit", "gold"]
total = words.inject(0.0){ |result, word| word.size + result}
total => 12.0
a = [1, 2, 3]
pp a.reverse => [3, 2, 1]
pp a =>[1, 2, 3]
a.reverse!
pp a => [3, 2, 1] hey_its_ordered = { first: 'mama', second: 'papa', third: 'baby' }
hey_its_ordered.each { |entry| pp entry }
[:first, "mama"]
[:second, "papa"]
[:third, "baby"] array.delete_if {|x| x < 0} %w[ruby is really nice].find { |item| item.length > 5 } => "really" %w[ruby is really nice].group_by { |item| item.length}
=> {4=>["ruby", "nice"], 2=>["is"], 6=>["really"]} %w[ruby is really nice].grep /rea/ => ["really"] a_string_with_a_quote = 'Say it ain\'t so!'
double_quoted = "I have a tab: \t and a newline: \n" author = "Ben Bova"
title = "Mars"
puts "#{title} is written by #{author}" str = '"Stop", she said, "I cannot deal with the backslashes." str = '"Stop", she said, "I can\'t live without \'s and "s."' str = %q{"Stop", she said, "I can't live without 's and "s."} str = %Q<The time in now #{Time.now}>
a_multiline_string = "a multi-line
string"
another_one = %q{another multi-line
string} yet_another = %Q{another multi-line string with \
no newline}
heres_one = <<RANDOM_TEXTof my here document. And this is the end. RANDOM _TEXT
' hello'.lstrip => 'hello' #rstrip #remove 1 unwanted newline at the end "It was a dark and stormy night\n".chomp => "It was a dark and stormy night\n".chomp "hello\n\n\n".chomp => "hello\n\n" #remove last character "hello".chop => "hell" #upcase/downcase 'Hello'.swapcase => 'hELLO'#substitute 1 occurance'It is warm outside'.sub( 'warm', 'cold' ) => "It is cold outside"#substitute allputs 'yes yes'.gsub( 'yes', 'no' ) => no no
#break into smaller parts'It was a dark and stormy night'.split=> ["It", "was", "a", "dark", "and", "stormy", "night"]'Bill:Shakespeare:Playwright:Globe'.split( ':' ) => ["Bill", "Shakespeare", "Playwright", "Globe"]#with regexps="http://www.website.com/dir1/dir2/file.txt"s.split /:\/\/|\.|\// => ["http", "www", "website", "com", "dir1", "dir2", "file", "txt"]#locate string"It was a dark and stormy night".index( "dark" ) => 9
"lol".each_char {|c| puts c}
l
o
l
"lol".each_byte {|b| puts b}
108
111
108 "some\n funky\n string\n here".each_line { |l| puts l}
some
funky
string
here
first_name = 'Karen' given_name = first_name #only 1 stringgiven_name << " Kowalski"first_name => "Karen Kowalski"
s = "omg" s.freeze s.frozen? => true s << "won't work" => RuntimeError: can't modify frozen String #unfreeze -> make new object s = "A new string" => "A new string"s.freeze s += "this will also work"=> "A new stringthis will also work"
first_name[-1]
Chapter 5
Find the Right String with
Regular Expressions
/\d\d:\d\d (AM|PM)/
puts /\d\d:\d\d (AM|PM)/ =~ '10:24 PM' => 0
puts '10:24 PM' =~ /PM/ => 6
/May/ =~ 'Sometime in June' => nil
'PM' =~ /am/i => 0
@content.gsub!( /\d\d:\d\d (AM|PM)/, '**:** **' )
content = 'The Princess And The Monkey
Once upon a time there was a princess...
...and they all lived happily ever after.
The End'
content =~ /^Once upon a time/ => 28 /^Once upon a time.*happily ever after\.$/m a = :all
b = :all
a == b => true
#check if objects are same
a.equal? b => true
s1 = "ruby"
s2 = "ruby"
s1 == s2 => true
s1.equal? s2 => false :all.to_s => 'all'
'string'.to_sym => :string person = {}
person[:name] = 'russ'
person[:eyes] = 'misty blue'
# A little later...
puts "Name: #{person['name']} Eyes: #{person['eyes']}" Classes are:"str".class => String "str".class.class => Class1.class => Fixnum # nil.class => NilClass false.class => FalseClass-3.class => Fixnum/regex/.class => Regexp:symbol.class => Symbol
doc = Document.new( 'Ethics', 'Spinoza', 'By that which is...' ) =>class Document
...
def about_me
puts "I am #{self}"
puts "My title is #{self.title}"
puts "I have #{self.word_count} words"
end
end class Foo
attr_writer :bar
def do_something
bar = 2
end
end "lol".class => String
"lol".instance_of? String => true
some_object.to_s => "#<0x00000001e75cb0>"
eval "puts 'hello'" => hello
"lol".public_methods => [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, ....]
class Document
def initialize
@name = "Borat"
end
end
d = Document.new
d.instance_variables => [:@name] class Document
# Most of the class omitted
private
# Methods are private starting here
def word_count
return words.size
end
end class Document # Most of the class omitted def word_count return words.size endprivate :word_count end
class Document
# Most of the class omitted...
def word_count
return words.size
end
private :word_count
# This method works because self is the right thing,
# the document instance, when you call it.
def print_word_count
n = word_count
puts "The number of words is #{word_count}"
end
end # RomanceNovel is a subclass of Document, # which is a subclass of Object class RomanceNovel < Document def number_of_steamy_words word_count / 4 # Works: self is a Document instance! end endrn = RomanceNovel.newrn.word_count =>NoMethodError: private method `word_count' called for <RomanceNovel:0x00000001049088>
n = doc.send( :word_count )