ruby programming language
DESCRIPTION
Ruby presentation @ Tchêlinux PelotasTRANSCRIPT
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
a_variable = 'a b c'.split(' ') #=> ['a','b','c']a_variable = a_variable.join(' ') #=> 'a b c'
def a_function object_parputs object_par.crazy_method
end
a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array
class Arraydef crazy_method
return 'crazy method for an array'end
end
a_function [1,2,3] #=> puts 'crazy method for an array'
a_variable = 'a b c'.split(' ') #=> ['a','b','c']a_variable = a_variable.join(' ') #=> 'a b c'
def a_function object_parputs object_par.crazy_method
end
a_function [1,2,3] #=> error: undefined method 'crazy_method' for class Array
class Arraydef crazy_method
return 'crazy method for an array'end
end
a_function [1,2,3] #=> puts 'crazy method for an array'
def a_function object_parputs 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_methodreturn 'this is a crazy feature'
end
a_function some_obj #=> puts 'this is a crazy_feature'
def a_function object_parputs 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_methodreturn 'this is a crazy feature'
end
a_function some_obj #=> puts 'this is a crazy_feature'
def square an_arrayreturn 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: ' + lineend
end
[1,2,3,4].select { |e| e.even? } #=> [2,4]
[1,2,3,4].collect { |e| e.even? } #=> [true,false,true,false]
[1,2,3,4].inject(0) { |sum,e| sum += e } #=> 10
class Books < Collectiondef initialize
@books = SomeReader.new('some_file_with_books').get_booksend
include Enumerable
def [email protected] { |book| yield(book) }
endend
Class Books now havemap, select, inject, grep, find_all, include?
and more
require 'test/unit'
class TestHtmlParser < Test::Unit::TestCase
must “find all imgs” doparser = 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']
endend
class HtmlParser
def initialize html_doc@content = html_doc
end
def [email protected](/img\s+src=\'(.+?)\'/)
endend
Standard Library
● erb - .rhtml● sockets● threads● html/xml parser● ftp, http, imap, pop3, smtp● tk● pstore