4. test_string = 'string for test'
puts 'matched' if test_string.match 'string'
files = Dir['*.txt']
for file in files
file_ref = open file
file_ref.each_line { |line| puts line.reverse.upcase }
end
5. Everything is an Object
10.times { puts “Hello World!” } “Hello World!”.methods
7. a_variable = 'a b c'.split(' ') #=> ['a','b','c']
a_variable = a_variable.join(' ') #=> 'a b c'
def a_function object_par
puts object_par.crazy_method
end
a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array
class Array
def crazy_method
return 'crazy method for an array'
end
end
a_function [1,2,3] #=> puts 'crazy method for an array'
8. a_variable = 'a b c'.split(' ') #=> ['a','b','c']
a_variable = a_variable.join(' ') #=> 'a b c'
def a_function object_par
puts object_par.crazy_method
end
a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array
class Array
def crazy_method
return 'crazy method for an array'
end
end
a_function [1,2,3] #=> puts 'crazy method for an array'
9. def a_function object_par
puts object_par.crazy_method
end
some_obj = SomeClass.new
a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass
def some_obj.crazy_method
return 'this is a crazy feature'
end
a_function some_obj #=> puts 'this is a crazy_feature'
10. def a_function object_par
puts object_par.crazy_method
end
some_obj = SomeClass.new
a_function some_obj #=> error: undefined method 'crazy_method' for class SomeClass
def some_obj.crazy_method
return 'this is a crazy feature'
end
a_function some_obj #=> puts 'this is a crazy_feature'
11. "if it walks like a duck and quacks like a
duck, then it is a duck”
13. def square an_array
return an_array.map { |e| e*e }
end
lines_of_a_doc.each_with_index do |line,i|
if i.even? then
puts 'even line: #{line}'
else
puts 'odd line: ' + line
end
end
17. class Books < Collection
def initialize
@books = SomeReader.new('some_file_with_books').get_books
end
include Enumerable
def each
@books.each { |book| yield(book) }
end
end
Class Books now have
map, select, inject, grep, find_all, include?
and more
19. require 'test/unit'
class TestHtmlParser < Test::Unit::TestCase
must “find all imgs” do
parser = HtmlParser.new '<div class='a'> <br/> <img src='img1.jpg'>n
<p><img src='img2.jpg'></body>'
assert_equal parser.parse_imgs, ['img1.jpg','img2.jpg']
end
end
class HtmlParser
def initialize html_doc
@content = html_doc
end
def parse_imgs
@content.scan(/imgs+src='(.+?)'/)
end
end