SlideShare una empresa de Scribd logo
1 de 58
Descargar para leer sin conexión
Ruby
  ihower@gmail.com




    http://creativecommons.org/licenses/by-nc/2.5/tw/
?
•              a.k.a. ihower
    •   http://ihower.idv.tw/blog/

    •   twitter: ihower

•        2006                   Ruby
•          (    )      Rails Developer
    •   http://handlino.com

    •   http://registrano.com
Ruby?
•
    (interpreted)

•
•
•            Yukihiro Matsumoto, a.k.a. Matz
    •           Lisp, Perl,   Smalltalk

    •                                     Happy
irb: Interactive Ruby

     irb(main):001:0>

     irb(main):001:0> 1 + 1
     => 2

     irb(main):002:0>
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++
?         ?
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;
Ruby
   #     "UPPER"
   puts "upper".upcase

   #     -5
   puts -5.abs

   #     Fixnum
   puts 99.class

   #     "Ruby Rocks!"
   5.times do
     puts "Ruby Rocks!"
   end
Array
a = [ 1, "cat", 3.14 ]

puts a[0] #        1
puts a.size #          3

a[2] = nil
puts a.inspect #           [1, "cat", nil]
Hash
             (Associative Array)


config = { "foo" => 123, "bar" => 456 }

puts config["foo"] #     123
Symbols

config = { :foo => 123, :bar => 456 }

puts config[:foo] #     123
If
if account.total > 100000
  puts "large account"
elsif account.total > 25000
  puts "medium account"
else
  puts "small account"
end
If
             if account.total > 100000
Perl Style     puts "large account"
             elsif account.total > 25000
               puts "medium account"
             else
               puts "small account"
             end
expression ? true_expresion : false_expression


    x = 3
    puts ( x > 3 )? "    " : "          "

    #
Case
case name
    when "John"
      puts "Howdy John!"
    when "Ryan"
      puts "Whatz up Ryan!"
    else
      puts "Hi #{name}!"
end
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
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
Regular Expressions
               Perl

  #

  phone = "123-456-7890"

  if phone   =~ /(d{3})-(d{3})-(d{4})/
    ext =    $1
    city =   $2
    num =    $3
  end
Methods
  def       end


def say_hello(name)
  result = "Hi, " + name
  return result
end

puts say_hello('ihower')
#     Hi, ihower
Methods
  def       end


def say_hello(name)
  result = "Hi, " + name
  return result
end

puts say_hello('ihower')
#     Hi, ihower
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
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
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
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
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
Class (             )


class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
Class (             )


class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
Class (             )


class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello, ihower
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
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
Class
class Pet
  attr_accessor :name, :age
end

class Cat < Pet
end

class Dog < Pet
end
code block
                              closure

{ puts "Hello" } #    block

do
      puts "Blah" #   block
      puts "Blah"
end
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 }
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
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]
code block

#
a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" }
#       ["a"]

#
[2,1,3].sort! { |a, b| b <=> a }
#       ["3",”2”,”1”]
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
code block
file = File.new("testfile", "r")
# ...
file.close



File.open("testfile", "r") do |file|
    # ...
end
#
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"
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!"
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!"
def my_sum(*val)
    val.inject(0) { |sum, v| sum + v }
end

puts my_sum(1,2,3,4)

#     10
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
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
Module (1) Namespace
  module MyUtil

        def self.foobar
            puts "foobar"
        end

  end

  MyUtil.foobar
  #     foobar
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"
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"
(duck typing)
#
class Duck
  def quack
    puts "quack!"
  end
end

#     (       )
class Mallard
  def quack
    puts "qwuaacck!! quak!"
  end
end
Class                     Type
birds = [Duck.new, Mallard.new, Object.new]

#
birds.each do |duck|
    duck.quack if duck.respond_to? :quack
end
Class                     Type
birds = [Duck.new, Mallard.new, Object.new]

#
birds.each do |duck|
    duck.quack if duck.respond_to? :quack
end
                      OOP
                         !
Metaprogramming
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"
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
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"
Introspection (                             )


#
Object.methods
=> ["send", "name", "class_eval", "object_id", "new",
"singleton_methods", ...]

#
Object.respond_to? :name
=> true
Ruby
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
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)
Thank you.




Beginning Ruby 2nd. (Apress)
Programming Ruby (The Pragmatic Programmers)
The Well-Grounded Rubyist (Manning)
Ruby           (O’Reilly)

Más contenido relacionado

La actualidad más candente

(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Rolessartak
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangSean Cribbs
 
Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Kang-min Liu
 
YAPC::Tiny Introduction
YAPC::Tiny IntroductionYAPC::Tiny Introduction
YAPC::Tiny IntroductionKang-min Liu
 
Helvetia
HelvetiaHelvetia
HelvetiaESUG
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma IntroduçãoÍgor Bonadio
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.Icalia Labs
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAhmed Salama
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchinaguestcf9240
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)lichtkind
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!Gautam Rege
 

La actualidad más candente (19)

(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
YAPC::Tiny Introduction
YAPC::Tiny IntroductionYAPC::Tiny Introduction
YAPC::Tiny Introduction
 
Language supports it
Language supports itLanguage supports it
Language supports it
 
Helvetia
HelvetiaHelvetia
Helvetia
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
Intro to ruby
Intro to rubyIntro to ruby
Intro to ruby
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!
 
Vim Hacks
Vim HacksVim Hacks
Vim Hacks
 

Destacado

Ruby on Rails 開發環境建置 for Mac
Ruby on Rails 開發環境建置 for MacRuby on Rails 開發環境建置 for Mac
Ruby on Rails 開發環境建置 for MacMarsZ Chen
 
Ruby on Rails为什么这么红?
Ruby on Rails为什么这么红?Ruby on Rails为什么这么红?
Ruby on Rails为什么这么红?Nathan Chen
 
Cognitive APIs and Conversational Interfaces
Cognitive APIs and Conversational InterfacesCognitive APIs and Conversational Interfaces
Cognitive APIs and Conversational InterfacesPavel Veller
 
Certbotで無料TLSサーバー
Certbotで無料TLSサーバーCertbotで無料TLSサーバー
Certbotで無料TLSサーバーKazuhiro Nishiyama
 
正規表現の先読みについて
正規表現の先読みについて正規表現の先読みについて
正規表現の先読みについてKazuhiro Nishiyama
 
Sublime Text 2 Tips & Tricks
Sublime Text 2 Tips & TricksSublime Text 2 Tips & Tricks
Sublime Text 2 Tips & TricksRhys Wynne
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Wen-Tien Chang
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateWen-Tien Chang
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingWen-Tien Chang
 
nadoka さんの m17n 対応のベストプラクティス
nadoka さんの m17n 対応のベストプラクティスnadoka さんの m17n 対応のベストプラクティス
nadoka さんの m17n 対応のベストプラクティスKazuhiro Nishiyama
 
hubot-slack v4移行時のハマりどころ #hubot_chatops
hubot-slack v4移行時のハマりどころ #hubot_chatopshubot-slack v4移行時のハマりどころ #hubot_chatops
hubot-slack v4移行時のハマりどころ #hubot_chatopsknjcode
 
lilo.linux.or.jp を wheezy から jessie にあげた話
lilo.linux.or.jp を wheezy から jessie にあげた話lilo.linux.or.jp を wheezy から jessie にあげた話
lilo.linux.or.jp を wheezy から jessie にあげた話Kazuhiro Nishiyama
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
程式設計首日封
程式設計首日封程式設計首日封
程式設計首日封政斌 楊
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2Wen-Tien Chang
 
分析路上你我他/如何學習分析
分析路上你我他/如何學習分析分析路上你我他/如何學習分析
分析路上你我他/如何學習分析Wanju Wang
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事Wen-Tien Chang
 

Destacado (20)

Ruby on Rails 開發環境建置 for Mac
Ruby on Rails 開發環境建置 for MacRuby on Rails 開發環境建置 for Mac
Ruby on Rails 開發環境建置 for Mac
 
Ruby on Rails为什么这么红?
Ruby on Rails为什么这么红?Ruby on Rails为什么这么红?
Ruby on Rails为什么这么红?
 
Cognitive APIs and Conversational Interfaces
Cognitive APIs and Conversational InterfacesCognitive APIs and Conversational Interfaces
Cognitive APIs and Conversational Interfaces
 
Rails I18n 20081125
Rails I18n 20081125Rails I18n 20081125
Rails I18n 20081125
 
Certbotで無料TLSサーバー
Certbotで無料TLSサーバーCertbotで無料TLSサーバー
Certbotで無料TLSサーバー
 
正規表現の先読みについて
正規表現の先読みについて正規表現の先読みについて
正規表現の先読みについて
 
Sublime Text 2 Tips & Tricks
Sublime Text 2 Tips & TricksSublime Text 2 Tips & Tricks
Sublime Text 2 Tips & Tricks
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
 
nadoka さんの m17n 対応のベストプラクティス
nadoka さんの m17n 対応のベストプラクティスnadoka さんの m17n 対応のベストプラクティス
nadoka さんの m17n 対応のベストプラクティス
 
hubot-slack v4移行時のハマりどころ #hubot_chatops
hubot-slack v4移行時のハマりどころ #hubot_chatopshubot-slack v4移行時のハマりどころ #hubot_chatops
hubot-slack v4移行時のハマりどころ #hubot_chatops
 
lilo.linux.or.jp を wheezy から jessie にあげた話
lilo.linux.or.jp を wheezy から jessie にあげた話lilo.linux.or.jp を wheezy から jessie にあげた話
lilo.linux.or.jp を wheezy から jessie にあげた話
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
Python webinar 2nd july
Python webinar 2nd julyPython webinar 2nd july
Python webinar 2nd july
 
HTTP Live Streaming
HTTP Live StreamingHTTP Live Streaming
HTTP Live Streaming
 
程式設計首日封
程式設計首日封程式設計首日封
程式設計首日封
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2
 
分析路上你我他/如何學習分析
分析路上你我他/如何學習分析分析路上你我他/如何學習分析
分析路上你我他/如何學習分析
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
 

Similar a Ruby 程式語言入門導覽

Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivoFabio Kung
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Crystal presentation in NY
Crystal presentation in NYCrystal presentation in NY
Crystal presentation in NYCrystal Language
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 

Similar a Ruby 程式語言入門導覽 (20)

An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby
RubyRuby
Ruby
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Rails by example
Rails by exampleRails by example
Rails by example
 
Crystal presentation in NY
Crystal presentation in NYCrystal presentation in NY
Crystal presentation in NY
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 

Más de Wen-Tien Chang

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨Wen-Tien Chang
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Wen-Tien Chang
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine LearningWen-Tien Chang
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事Wen-Tien Chang
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upWen-Tien Chang
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩Wen-Tien Chang
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0Wen-Tien Chang
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean StartupWen-Tien Chang
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingWen-Tien Chang
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試Wen-Tien Chang
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Wen-Tien Chang
 

Más de Wen-Tien Chang (20)

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine Learning
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
 
Git Tutorial 教學
Git Tutorial 教學Git Tutorial 教學
Git Tutorial 教學
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試
 
Git and Github
Git and GithubGit and Github
Git and Github
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
 

Ruby 程式語言入門導覽

  • 1. Ruby ihower@gmail.com http://creativecommons.org/licenses/by-nc/2.5/tw/
  • 2. ? • a.k.a. ihower • http://ihower.idv.tw/blog/ • twitter: ihower • 2006 Ruby • ( ) Rails Developer • http://handlino.com • http://registrano.com
  • 3. Ruby? • (interpreted) • • • Yukihiro Matsumoto, a.k.a. Matz • Lisp, Perl, Smalltalk • Happy
  • 4. irb: Interactive Ruby irb(main):001:0> irb(main):001:0> 1 + 1 => 2 irb(main):002:0>
  • 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. ? ? 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. Ruby # "UPPER" puts "upper".upcase # -5 puts -5.abs # Fixnum puts 99.class # "Ruby Rocks!" 5.times do puts "Ruby Rocks!" end
  • 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. Hash (Associative Array) config = { "foo" => 123, "bar" => 456 } puts config["foo"] # 123
  • 10. Symbols config = { :foo => 123, :bar => 456 } puts config[:foo] # 123
  • 11. If if account.total > 100000 puts "large account" elsif account.total > 25000 puts "medium account" else puts "small account" end
  • 12. If if account.total > 100000 Perl Style puts "large account" elsif account.total > 25000 puts "medium account" else puts "small account" end
  • 13. expression ? true_expresion : false_expression x = 3 puts ( x > 3 )? " " : " " #
  • 14. Case case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!" end
  • 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. 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. Regular Expressions Perl # phone = "123-456-7890" if phone =~ /(d{3})-(d{3})-(d{4})/ ext = $1 city = $2 num = $3 end
  • 18. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  • 19. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  • 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. 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. 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. 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. 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. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 26. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 27. Class ( ) class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  • 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. 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. Class class Pet attr_accessor :name, :age end class Cat < Pet end class Dog < Pet end
  • 31. code block closure { puts "Hello" } # block do puts "Blah" # block puts "Blah" end
  • 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. 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. 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. 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. 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. code block file = File.new("testfile", "r") # ... file.close File.open("testfile", "r") do |file| # ... end #
  • 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. 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. 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. def my_sum(*val) val.inject(0) { |sum, v| sum + v } end puts my_sum(1,2,3,4) # 10
  • 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. 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. Module (1) Namespace module MyUtil def self.foobar puts "foobar" end end MyUtil.foobar # foobar
  • 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. 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. (duck typing) # class Duck def quack puts "quack!" end end # ( ) class Mallard def quack puts "qwuaacck!! quak!" end end
  • 48. Class Type birds = [Duck.new, Mallard.new, Object.new] # birds.each do |duck| duck.quack if duck.respond_to? :quack end
  • 49. Class Type birds = [Duck.new, Mallard.new, Object.new] # birds.each do |duck| duck.quack if duck.respond_to? :quack end OOP !
  • 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. 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. 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. Introspection ( ) # Object.methods => ["send", "name", "class_eval", "object_id", "new", "singleton_methods", ...] # Object.respond_to? :name => true
  • 55. Ruby
  • 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. 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. Thank you. Beginning Ruby 2nd. (Apress) Programming Ruby (The Pragmatic Programmers) The Well-Grounded Rubyist (Manning) Ruby (O’Reilly)