Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Ruby 程式語言入門導覽

3,482 views

Published on

  • Be the first to comment

Ruby 程式語言入門導覽

  1. 1. Ruby ihower@gmail.com http://creativecommons.org/licenses/by-nc/2.5/tw/
  2. 2. ? • a.k.a. ihower • http://ihower.idv.tw/blog/ • twitter: ihower • 2006 Ruby • ( ) Rails Developer • http://handlino.com • http://registrano.com
  3. 3. Ruby? • (interpreted) • • • Yukihiro Matsumoto, a.k.a. Matz • Lisp, Perl, Smalltalk • Happy
  4. 4. irb: Interactive Ruby irb(main):001:0> irb(main):001:0> 1 + 1 => 2 irb(main):002:0>
  5. 5. Ruby • Dynamic v.s. Static typing • Ruby/Perl/Python/PHP v.s. Java/C/C++ • Strong v.s. Weak typing • Ruby/Perl/Python/Java v.s. PHP/C/C++
  6. 6. ? ? PHP code: Ruby code: $i = 1; i=1 echo "Value is " + $i puts "Value is " + i # 1 #TypeError: can't convert Fixnum into String # from (irb):2:in `+' C code: # from (irb):2 int a = 5; float b = a;
  7. 7. Ruby # "UPPER" puts "upper".upcase # -5 puts -5.abs # Fixnum puts 99.class # "Ruby Rocks!" 5.times do puts "Ruby Rocks!" end
  8. 8. Array a = [ 1, "cat", 3.14 ] puts a[0] # 1 puts a.size # 3 a[2] = nil puts a.inspect # [1, "cat", nil]
  9. 9. Hash (Associative Array) config = { "foo" => 123, "bar" => 456 } puts config["foo"] # 123
  10. 10. Symbols config = { :foo => 123, :bar => 456 } puts config[:foo] # 123
  11. 11. If if account.total > 100000 puts "large account" elsif account.total > 25000 puts "medium account" else puts "small account" end
  12. 12. If if account.total > 100000 Perl Style puts "large account" elsif account.total > 25000 puts "medium account" else puts "small account" end
  13. 13. expression ? true_expresion : false_expression x = 3 puts ( x > 3 )? " " : " " #
  14. 14. Case case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!" end
  15. 15. while, loop, until, next and break i=0 i = 0 while ( i < 10 ) loop do i += 1 i += 1 next if i % 2 == 0 # break if i > 10 # end end i = 0 i += 1 until i > 10 puts i # 11
  16. 16. false nil puts "not execute" if nil puts "not execute" if false puts "execute" if true # execute puts "execute" if “” # execute ( JavaScript ) puts "execute" if 0 # execute ( C ) puts "execute" if 1 # execute puts "execute" if "foo" # execute puts "execute" if Array.new # execute
  17. 17. Regular Expressions Perl # phone = "123-456-7890" if phone =~ /(d{3})-(d{3})-(d{4})/ ext = $1 city = $2 num = $3 end
  18. 18. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  19. 19. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  20. 20. Class class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  21. 21. Class class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  22. 22. Class class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  23. 23. Class class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  24. 24. Class class Greeter def initialize(name) @name = name end def say(word) puts "#{word}, #{@name}" end end g1 = Greeter.new("ihower") g2 = Greeter.new("ihover") g1.say("Hello") # Hello, ihower g2.say("Hello") # Hello, ihover
  25. 25. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  26. 26. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  27. 27. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  28. 28. Class body attr_accessor, attr_writer, attr_reader class Person class Person def name @name attr_accessor :name end end def name=(val) @name = val end end
  29. 29. class MyClass class MyClass def public_method def public_method end end private def private_method end def private_method end def protected_method end protected public :public_method def protected_method private :private_method end protected :proected_method end end
  30. 30. Class class Pet attr_accessor :name, :age end class Cat < Pet end class Dog < Pet end
  31. 31. code block closure { puts "Hello" } # block do puts "Blah" # block puts "Blah" end
  32. 32. code block (iterator) # people = ["David", "John", "Mary"] people.each do |person| puts person end # 5.times { puts "Ruby rocks!" } # 1.upto(9) { |x| puts x }
  33. 33. code block (iterator) # people = ["David", "John", "Mary"] people.each do |person| puts person end # 5.times { puts "Ruby rocks!" } # 1.upto(9) { |x| puts x } while, until, for
  34. 34. code block # a = [ "a", "b", "c", "d" ] b = a.map {|x| x + "!" } puts b.inspect # ["a!", "b!", "c!", "d!"] # b = [1,2,3].find_all{ |x| x % 2 == 0 } b.inspect # [2]
  35. 35. code block # a = [ "a", "b", "c" ] a.delete_if {|x| x >= "b" } # ["a"] # [2,1,3].sort! { |a, b| b <=> a } # ["3",”2”,”1”]
  36. 36. code block functional programming fu? # (5..10).inject {|sum, n| sum + n } # find the longest word longest = ["cat", "sheep", "bear"].inject do |memo, word| ( memo.length > word.length )? memo : word end
  37. 37. code block file = File.new("testfile", "r") # ... file.close File.open("testfile", "r") do |file| # ... end #
  38. 38. Yield yield code block # def call_block puts "Start" yield yield puts "End" end call_block { puts "Blocks are cool!" } # # "Start" # "Blocks are cool!" # "Blocks are cool!" # "End"
  39. 39. code block def call_block yield(1) yield(2) yield(3) end call_block { |i| puts "#{i}: Blocks are cool!" } # # "1: Blocks are cool!" # "2: Blocks are cool!" # "3: Blocks are cool!"
  40. 40. Proc object code block def call_block(&block) block.call(1) block.call(2) block.call(3) end call_block { |i| puts "#{i}: Blocks are cool!" } # proc object proc_1 = Proc.new { |i| puts "#{i}: Blocks are cool!" } proc_2 = lambda { |i| puts "#{i}: Blocks are cool!" } call_block(&proc_1) call_block(&proc_2) # # "1: Blocks are cool!" # "2: Blocks are cool!" # "3: Blocks are cool!"
  41. 41. def my_sum(*val) val.inject(0) { |sum, v| sum + v } end puts my_sum(1,2,3,4) # 10
  42. 42. Hash {} def my_print(a, b, options) puts a puts b puts options[:x] puts options[:y] puts options[:z] end puts my_print("A", "B", { :x => 123, :z => 456 } ) puts my_print("A", "B", :x => 123, :z => 456) # # A # B # 123 # nil # 456
  43. 43. raise, begin, rescue, ensure begin raise "Not works!!" puts 10 / 0 # RuntimeError rescue => e puts e.class # ensure class MyException < RuntimeError # ... end end raise MyException # ZeroDivisionError
  44. 44. Module (1) Namespace module MyUtil def self.foobar puts "foobar" end end MyUtil.foobar # foobar
  45. 45. Module(2) Mixins module Debug def who_am_i? "#{self.class.name} (##{self.object_id}): #{self.to_s}" end end class Foo include Debug # Mixin # ... end class Bar include Debug include AwesomeModule # ... end ph = Foo.new("12312312") et = Bar.new("78678678") ph.who_am_i? # "Foo (#330450): 12312312" et.who_am_i? # "Bar (#330420): 78678678"
  46. 46. Module(2) Mixins module Debug def who_am_i? "#{self.class.name} (##{self.object_id}): #{self.to_s}" end end class Foo include Debug # Mixin # ... end class Bar include Debug include AwesomeModule # ... Ruby end Module ph = Foo.new("12312312") et = Bar.new("78678678") ph.who_am_i? # "Foo (#330450): 12312312" et.who_am_i? # "Bar (#330420): 78678678"
  47. 47. (duck typing) # class Duck def quack puts "quack!" end end # ( ) class Mallard def quack puts "qwuaacck!! quak!" end end
  48. 48. Class Type birds = [Duck.new, Mallard.new, Object.new] # birds.each do |duck| duck.quack if duck.respond_to? :quack end
  49. 49. Class Type birds = [Duck.new, Mallard.new, Object.new] # birds.each do |duck| duck.quack if duck.respond_to? :quack end OOP !
  50. 50. Metaprogramming
  51. 51. define_method class Dragon define_method(:foo) { puts "bar" } ['a','b','c','d','e','f'].each do |x| define_method(x) { puts x } end end dragon = Dragon.new dragon.foo # "bar" dragon.a # "a" dragon.f # "f"
  52. 52. Domain-Specific Language class Firm < ActiveRecord::Base has_many :clients has_one :account belongs_to :conglomorate end # has_many AciveRecord class method Firm instance methods firm = Firm.find(1) firm.clients firm.clients.size firm.clients.build firm.clients.destroy_all
  53. 53. Method Missing class Proxy def initialize(object) @object = object end def method_missing(symbol, *args) @object.send(symbol, *args) end end object = ["a", "b", "c"] proxy = Proxy.new(object) puts proxy.first # Proxy first method_missing "a"
  54. 54. Introspection ( ) # Object.methods => ["send", "name", "class_eval", "object_id", "new", "singleton_methods", ...] # Object.respond_to? :name => true
  55. 55. Ruby
  56. 56. Ruby production • Ruby 1.8.6, 1.8.7 ( MRI, Matz’ Ruby Interpreter) • Ruby 1.9.1 (YARV) • JRuby • Ruby1.8.6 1.9 • Ruby Enterprise Edition(REE) • Ruby 1.8.6 GC memory leak
  57. 57. Ruby production • IronRuby (based on Microsoft .NET) • MacRuby (based on Objective-C) • Rubinius (Engine yard project) • MagLev (based on smalltalk) • Cardinal (based on Parrot VM)
  58. 58. Thank you. Beginning Ruby 2nd. (Apress) Programming Ruby (The Pragmatic Programmers) The Well-Grounded Rubyist (Manning) Ruby (O’Reilly)

×