Successfully reported this slideshow.

Ruby basic2



Upcoming SlideShare
Algorithm  2
Algorithm 2
Loading in …3
1 of 15
1 of 15

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

Ruby basic2

  1. 1. Ruby Basic (2) Author: Jason
  2. 2. Content Method Regular Expression Block Iterator Convention
  3. 3. Method No type in parameter since Ruby is dynamic last expression value will be returned But You can explicitly state the return statement
  4. 4. Method Example def say_goodnight(name) "Good night, " + name end say_goodnight("jason") # => "Good night, jason" return
  5. 5. Common method Method Usage print print content with no line break puts print content with line break p same as puts but more detailed
  6. 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. 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. 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. 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
  10. 10. Block Example Single expression { puts "hello" } Many expressions do puts "hello" puts "world" end
  11. 11. Called by function? def greet yield puts "Jason" end greet { puts "Hi" } Result: Hi Jason code in {} will be placed in yield
  12. 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. 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. 14. Iterator Example names = %w{jason sam ray} names.each do |name| print "Weclome, " puts name end Result: Weclome, jason Weclome, sam Weclome, ray
  15. 15. Convention