Ruby101

406 views

Published on

Beginning ruby for programmers. Overview of ruby covering the basics

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
406
On SlideShare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ruby101

  1. 1. Ruby 1011Thursday, April 18, 13
  2. 2. Topics• Ruby Syntax• Methods/Functions• DataTypes• Control Flow• Exceptions2Thursday, April 18, 13
  3. 3. Ruby Syntax3Thursday, April 18, 13
  4. 4. Ruby Syntax• indent 2 spaces, no tabs• CamelCase for class names• snake_case_for methods and variables• filenames always snake caseuser_setting.rbclass UserSettingdef update_from_params(params)enddef saveendend 4Thursday, April 18, 13
  5. 5. Ruby Syntax• comments start with #• multi-line =begin =end# one line comment=beginname = "Bob"address = "123 street"city = "Any Town"=end5Thursday, April 18, 13
  6. 6. parentheses optional(mostly!)need them hereelse will an OR hereDocument.new "The Ruby Way", "Hal Fulton"Document.new("The Ruby Way", "Hal Fulton")event_date.to_s :shortevent_date.to_s(:short)if name.blank?puts "Hi nobody"endif (name.blank? || (name == "bob"))if name.blank? || (name == "bob")if name.blank? || name == "bob"6Thursday, April 18, 13
  7. 7. one more thing aboutparenthesesclass Userdef status#blah blahendendclass Userdef status()#blah blahendendalwaysnever7Thursday, April 18, 13
  8. 8. Variables8$global_variable@@class_variable@instance_variableCONSTANTThursday, April 18, 13
  9. 9. String Interpolationvs String Concatenation10.times { |n| puts "the number is #{n}" }String Interpolation, plus reads better10.times { |n| puts "the number is" + n }String concatenation, slow-er!plus calls to_s if not a string9Thursday, April 18, 13
  10. 10. • code style• variable/class style• comments• role of parentheses• variables• string interpolation10Learned about Ruby SyntaxThursday, April 18, 13
  11. 11. Methods11functions usually called methodsThursday, April 18, 13
  12. 12. Method Return Values12def format_name(user)return "#{user.first.capitalize} #{user.last.capitalize}"enddef format_name(user)"#{user.first.capitalize} #{user.last.capitalize}"endLast line of function is implicit returnThursday, April 18, 13
  13. 13. methods with ? !13def validate_user?(user)if user.first.present? && user.last.present?trueelsefalseendenddef promote_user!(user, level)user.access = leveluser.saveendThursday, April 18, 13
  14. 14. methods with ?14> "classified ventures".include?("class")=> true> "classified ventures".include?("blah")=> falseUse ? as part of the method name if itreturns a booleanThursday, April 18, 13
  15. 15. Using !15> company = "classified ventures"=> "classified ventures"> company.upcase=> "CLASSIFIED VENTURES"> company=> "classified ventures"> company.upcase!=> "CLASSIFIED VENTURES"> company=> "CLASSIFIED VENTURES"Thursday, April 18, 13
  16. 16. Learned about• ! methods• ? methods• return value16Thursday, April 18, 13
  17. 17. Data TypesEverything is an objectno such idea as “primitives”17Thursday, April 18, 13
  18. 18. Strings> company = "Classified Ventures"=> "Classified Ventures"> company.length=> 19> company.reverse=> "serutneV deifissalC"> company.upcase=> "CLASSIFIED VENTURES"> company.start_with?("Class")=> true> company.start_with?("Goo")=> false18Thursday, April 18, 13
  19. 19. Symbols> :first=> :first> :first.class=> SymbolCommonly used in Hashes19Thursday, April 18, 13
  20. 20. Whats the difference?> "hello".object_id=> 70312121540820> "hello".object_id=> 70312126306720> :first.object_id=> 32488> :first.object_id=> 3248820Thursday, April 18, 13
  21. 21. FixNum,BigNum,Booleans> 1.class=> Fixnum> 10000000000000000000000000.class=> Bignum> 3.14.class=> Float> true.class=> TrueClass> false.class=> FalseClass21Thursday, April 18, 13
  22. 22. Arraysfruits = [apple, orange, pear]fruits = %w(apple orange pear)=> [apple, orange, pear]a = Array.new(5)=> [nil, nil, nil, nil, nil]a = Array.new(5, "--")=> ["--", "--", "--", "--", "--"]22Thursday, April 18, 13
  23. 23. Hashesdefault value if key is not foundfruits = {:apple => 5, :orange => 4, :pear => 1}fruits = { apple: 5, orange: 4, pear: 1 }fruits[:apple]=> 5z = {} #default is nila = Hash.new( "--" ) #default is “--”z[:blah]=> nila[:blah]=> "--"Ruby 1.923Thursday, April 18, 13
  24. 24. Struct24Crumb = Struct.new(:name, :value)=> Crumbhome = Crumb.new("Home", "/")=> #<struct Crumb name="Home", value="/">home=> #<struct Crumb name="Home", value="/">> home.name=> "Home"> home.value=> "/"Thursday, April 18, 13
  25. 25. Ranges25> 1..10=> 1..10> (1..10).class=> Range> (1..10).to_a (creates array)=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]> (1...10).to_a=> [1, 2, 3, 4, 5, 6, 7, 8, 9]two dots includes end pointthree dots does not include end pointThursday, April 18, 13
  26. 26. Learned about Datatypes• Strings• Symbols• FixNum, BigNum• Booleans• Array• Hash• Struct• Ranges26Thursday, April 18, 13
  27. 27. Practice• www.rubykoans.com• http://www.zenspider.com/Languages/Ruby/QuickRef.html27Thursday, April 18, 13
  28. 28. Classesclass Documentattr_accessor :title, :author, :contentdef initialize(title, author, content)@title = title@author = author@content = contentendend@var is an instance variableaccess it as @var inside class28constructorThursday, April 18, 13
  29. 29. attr_accessormakes getters and settersclass Document# setterdef title=(title)@title = titleend# getterdef title@titleendclass Documentattr_accessor :titleendsame resultalso attr_reader and attr_writer29Thursday, April 18, 13
  30. 30. Example Classclass Documentattr_accessor :title, :authordef initialize(title, author)@title = title@author = authorenddef words@content.splitenddef self.supported_file_types%w(pdf jpg gif doc)endenddoc = Document.new("The Ruby Way", "Fulton")doc.wordsDocument.supported_file_types30instance methodclass methodThursday, April 18, 13
  31. 31. Learned about• class constructors• getters/setters• instance methods• static methods31Thursday, April 18, 13
  32. 32. Control Flow32Thursday, April 18, 13
  33. 33. Code Blocks10.times { |n| puts "the number is #{n}" }10.times do |n|puts "the number is #{n}"better_for_longer_blocks(n)end33item for each iteration is nThursday, April 18, 13
  34. 34. if / unlessif not @readonlydoc.write(text)endunless @readonlydoc.write(text)endunless @readonlydoc.write(text)elselog.warn("attempt to write to readonly file")enddoc.write(text) unless @readonlybadgoodgoodbad34Thursday, April 18, 13
  35. 35. for / eachfruits = [apple, orange, pear]for fruit in fruitsputs fruitendfruits.each do |fruit|puts fruitendbadgood35Thursday, April 18, 13
  36. 36. while loops36i = 0while i < 5puts ii += 1endi = 0until i == 5puts ii += 1endputs i += 1 until i == 5Thursday, April 18, 13
  37. 37. Exceptions37class Name# Define default getter method, but not setter method.attr_reader :first# When someone tries to set a first name, enforce rules about it.def first=(first)if first.blank?raise ArgumentError.new(Everyone must have a first name.)end@first = first.capitalizeendenddef editname = Name.newname.first = params[:name]rescue ArgumentError => elog.error("Validation Error #{e.message}")endThursday, April 18, 13
  38. 38. Covered Control Flow• if/unless• for/each• while loops• exceptions38Thursday, April 18, 13

×