View
241
Download
1
Category
Preview:
Citation preview
Ruby Basic (2)Author: Jason
Content
Method
Regular Expression
Block
Iterator
Convention
Method
No type in parameter since Ruby is dynamic
last expression value will be returned
But You can explicitly state the return statement
Method Example
def say_goodnight(name)
"Good night, " + name
end
say_goodnight("jason") # => "Good night, jason"
return
Common method
Method Usage
print print content with no line break
puts print content with line break
p same as puts but more detailed
Regular Expression
Ruby is built in with Regular Expression
Regular Expression is also a class in Ruby
patten = /Perl|Python/
patten.class # => Regexp
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
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"
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
Block Example
Single expression
{ puts "hello" }
Many expressions
do
puts "hello"
puts "world"
end
Called by function?def greet
yield
puts "Jason"
end
greet { puts "Hi" }
Result:
Hi
Jason
code in {} will be placed in yield
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
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
Iterator Examplenames = %w{jason sam ray}
names.each do |name|
print "Weclome, "
puts name
end
Result:
Weclome, jason
Weclome, sam
Weclome, ray
Convention
Recommended