6. Regular Expression
Ruby is built in with Regular Expression
Regular Expression is also a class in Ruby
patten = /Perl|Python/
patten.class # => Regexp
7. Find with Regex
Use =~ to find that String contains pattern or
not
line = "Perl"
if line =~ /Perl|Python/
puts "line contain Perl or Python"
end
8. Substitution with Regex
line = "Perl, Perl , Perl"
sub : substitute first occurrence
line.sub(/Perl/,"Ruby") # => "Ruby, Perl , Perl"
gsub: substitute all occurrence
line.gsub(/Perl/,"Ruby") # => "Ruby, Ruby , Ruby"
9. Block
You may consider block as a anonymous
function called by another method
By Convention:
Single expression inside block use {}
Many expressions inside block use do..end
11. Called by function?
def greet
yield
puts "Jason"
end
greet { puts "Hi" }
Result:
Hi
Jason
code in {}
will be placed in yield
12. Block with argument
def greet
yield("Jason")
end
greet { |name| puts "Hello, #{name}" }
Result: Hello, Jason
PS: It does’t matter what your variable name is
inside |..|
"Jason" become name
13. Iterator
Many iterator can take a block
Iterator can help you loop though an array
and do some operations
A basic iterator is .each which loop all of the
element in the array
14. Iterator Example
names = %w{jason sam ray}
names.each do |name|
print "Weclome, "
puts name
end
Result:
Weclome, jason
Weclome, sam
Weclome, ray