Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby by Example

Ruby by Example

0b2600a627d0af06ca6bbf9abe4067af?s=128

James Hughes

June 22, 2012
Tweet

More Decks by James Hughes

Other Decks in Programming

Transcript

  1. RUBY BY EXAMPLE

  2. Ruby is... interpreted object oriented dynamic

  3. Ruby is... productive intuitive popular

  4. VARIABLES & TYPES

  5. Before we begin... a.+(b) a.is_valid? a.decrement!

  6. $counter @@counter @counter counter Global Class Instance Local

  7. ‘hello’ ‘’‘hello’’’ %q{hello} String Herestring Perl-inspired

  8. a = ‘James’ b = “Hello #{a}” puts b =>

    “Hello James”
  9. :hello Symbol

  10. puts <<DOC This is a "heredoc" Multi-line String DOC

  11. [1,2,3] {:a=>1, :b=>2} {a: 1, b: 2} 0..10 Array Hash

    (1.8) Hash (1.9) Ranges
  12. METHODS

  13. def greet(name) “Hello, #{name}” end greet “James”

  14. def greet(name=“World”) “Hello, #{name}” end greet “James” greet

  15. CONTROL FLOW

  16. if rating >= 4 puts "great" elsif rating == 3

    puts "alright" else puts "sucks" end
  17. unless rating == 5 puts “Try harder” end

  18. puts “Try harder” unless rating == 5 puts “Seriously” if

    rating == 1
  19. case rating when 4..5 puts "great" when 3 puts "alright"

    else puts "sucks" end
  20. while !le.has_more_lines? puts !le.next_line end puts !le.next_line while !le.has_more_lines?

  21. until !le.end_of_!le? puts !le.next_line end puts !le.next_line until !le.end_of_!le?

  22. for i in 0...!le.line_count puts !le.lines[i] end

  23. BLOCKS

  24. [1,2,3,4].each do |i| puts i end

  25. array.each(&block)

  26. printer = Proc.new do |i| puts i end [1,2,3,4].each &printer

  27. printer = lambda { |i| puts i }

  28. def loggerWrapper puts "Executing Method" yield puts "Done Executing" end

    loggerWrapper { puts "Weeee!" }
  29. COLLECTIONS

  30. Array/Enumerable Operations 109 Hash Operations 50

  31. [1,2,3,4,5].map { |i| i +1} [1,2,3,4,5].reduce { |i, j| i

    + j } ({a: '1'}).merge({b: '2'})
  32. CLASSES

  33. class Person def initialize(name, age) @name,@age = name,age end end

    person = Person.new("James", 32)
  34. class Person attr_accessor :name attr_accessor :age ... end p =

    Person.new("James", 32) puts p.name, p.age
  35. class Person ... end class Hero < Person attr_accessor :powers

    end p = Hero.new("James", 32) p.powers = [“Flying”]
  36. MODULES & MIXINS

  37. module StrUtils def self.salt(pass, slt) “#{pass}#{salt}” end def salt(slt) StrUtils::salt(@value,

    slt) end end
  38. StrUtils::salt("123", "456")

  39. class Password include Utils def initialize(value) @value = value end

    end Password.new("test").salt
  40. TOOLS OF THE TRADE

  41. irb Interactive shell ruby Ruby interpreter gem Library manager rake

    Build tool rails Web framework
  42. RUBY BY EXAMPLE