0
Ruby
  ihower@gmail.com




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

    •   http://twitter.com/ihower

•        2006       ...
?

•          a.k.a Ryudo
    • http://www.freebbs.tw
    • http://www.gameckub.tw
• 2007              Rails
• TOMLAN     ...
Ruby?
•
    (interpreted)

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

    •...
•           Ruby 1.8.6 One-click Installer
• http://www.ruby-lang.org/en/downloads/
• Next -> Agree -> Enable Rubygems
Part1:
irb: Interactive Ruby

     irb(main):001:0>

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

     irb(main):002:0> 100 * 5 + 99
PUTS

•       notepad++         hello.rb
    puts "Hello World!"

•       ruby number.rb
Integer

5
-205
9999999999
0
Float
     .



54.321
0.001
-12.312
0.0
puts   1.0   +   2.0
puts   2.0   *   3.0
puts   5.0   -   8.0
puts   9.0   /   2.0

#   3.0
#   6.0
#   -3.0
#   4.5
puts     1   +   2
puts     2   *   3
puts     5   -   8
puts     9   /   2

#   3
#   6
#   -1
#   4
puts 5 * (12-8) + -15
puts 98 + (59872 / (13*8)) * -52
String

puts 'Hello, world!'
puts ''
puts 'Good-bye.'
puts 'I like ' + 'apple pie.'
puts 'You're smart!'

puts '12' + 12
#<TypeError: can't convert Fixnum into String>
Variable

composer = 'Mozart'
puts composer + ' was "da bomb", in his day.'

composer = 'Beethoven'
puts 'But I prefer ' +...
Conversions
var1 = 2
var2 = '5'

puts var1.to_s + var2 # 25
puts var1 + var2.to_i # 7

puts 9.to_f / 2 # 4.5
GETS
puts 'Hello there, and what's your name?'

name = gets.chomp

puts 'Your name is ' + name + '? What a lovely name!'
p...
Methods
•                      (Object)


•          .
•                                 self
    puts   self.puts
var1 = 'stop'
var2 = 'foobar'
var3 = "aAbBcC"

puts   var1.reverse # 'pots'
puts   var2.length # 6
puts   var3.upcase
puts...
Flow Control
puts   1   > 2
puts   1   < 2
puts   5   >= 5
puts   5   <= 4
puts   1   == 1
puts   2   != 1

puts ( 2 > 1 ) && ( 2 > 3 )...
false     nil

puts "not execute" if nil
puts "not execute" if false

puts   "execute"   if   true #      execute
puts   "...
puts "hello, who are you?"

name = gets.chomp

if name == "you"
     puts "that's you"
elsif name == "me"
     puts "that'...
Case
case name
    when "John"
      puts "Howdy John!"
    when "Ryan"
      puts "Whatz up Ryan!"
    else
      puts "H...
command = ''

while command != 'bye'
  puts command
  command = gets.chomp
end

puts 'Come again soon!'
Array
a = [ 1, "cat", 3.14 ]

puts a[0] #     1
puts a[1] #     “cat”
puts a.size #     3
colors = ["red", "blue"]

colors.push("black")
colors << "white"
puts colors.join(", ") # red, blue, black, white

colors....
each method


languages = ['Ruby', 'Javascript', 'Perl']

languages.each do |lang|
  puts 'I love ' + lang + '!'
end

# I ...
iterator
•     while                  each

     (iterator)
•   do .... end    each
             ( code block)
3.times do
  puts 'Good Job!'
end

# Good Job!
# Good Job!
# Good Job!
code block
                              closure

{ puts "Hello" } #    block

do
      puts "Blah" #   block
      puts "...
code block
#
a = [ "a", "b", "c", "d" ]
b = a.map {|x| x + "!" }
puts b.inspect
#       ["a!", "b!", "c!", "d!"]

#
b = [1...
code block
file = File.new("testfile", "r")
# ...
file.close



File.open("testfile", "r") do |file|
    # ...
end
#
Hash
             (Associative Array)


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

puts config["foo"] #     123
Symbols

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

puts config[:foo] #     123
Methods
  def       end


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

puts say_hello('ihower')
#    ...
Methods
  def       end


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

puts say_hello('ihower')
#    ...
Person                          Class


                            Attributes     Methods




john = Person.new          ...
Classes
          new

color_string = String.new
color_string = "" #

color_array = Array.new
color_array = [] #

color_ha...
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #...
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #...
class Greeter

      def initialize(name)
          @name = name
      end

      def say(word)
          puts "#{word}, #...
class Greeter

      def initialize(name)
          @name = name
      end
                                        (   )
 ...
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello...
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello...
class Greeter

      @@name = “ihower”

      def self.say
          puts @@name
      end

end

Greeter.say #       Hello...
attr_accessor, attr_writer, attr_reader

                                     class Person

class Person                  ...
Part2:
   gem install sinatra -y --no-ri --no-rdoc
  gem install nokogiri -y --no-ri --no-rdoc
RubyGems

• Ruby
• gem list
•            http://gemcutter.org/
Sinatra

•                     web development
• http://www.sinatrarb.com/
• gem install sinatra
web app
ruby myapp.rb                        http://localhost:4567


                # myapp.rb
                require 'r...
URL
require 'rubygems'
require 'sinatra'

get '/hello/:name' do
    #     "GET /hello/foo"    "GET /hello/bar"
    # param...
template
views             hello.erb


   # myapp.rb
   require 'rubygems'
   require 'sinatra'

   get '/hello/:name' do
...
ERB (Ruby Template)
 <!DOCTYPE html>
 <html>
 <head>
    <title>Sinatra app</title>
 </head>
 <body>
   <% 10.times do %>
...
Template
# myapp.rb
require 'rubygems'
require 'sinatra'

get '/array' do
    @arr = ["aaa","bbb","ccc","ddd"]
    erb :ar...
# myapp.rb          # views/index.erb
require 'rubygems'   <form action="/query" method="post">
require 'sinatra'
        ...
nokogiri

• HTML, XML, SAX         (parser)
•      XPath     CSS
• gem install nokogiri
require 'rubygems'
require 'nokogiri'

text = "<html>
  <ul>
    <li>FOOOBARRR</li>
    <li>AAAAACCCCC</li>
  <ul>
</html>...
sinatra+nokogiri
   # myapp.rb
   require 'rubygems'
   require 'sinatra'
   require 'nokogiri'
   require 'open-uri'

   ...
<!DOCTYPE html>
<html>
<head>
   	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>...
Thank you.




Learn to Program http://pine.fm/LearnToProgram/
Beginning Ruby 2nd. (Apress)
Upcoming SlideShare
Loading in...5
×

Ruby 入門 第一次就上手

7,464

Published on

0 Comments
25 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,464
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
261
Comments
0
Likes
25
Embeds 0
No embeds

No notes for slide

Transcript of "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/ • http://twitter.com/ihower • 2006 Ruby • ( ) Rails Developer • http://handlino.com • http://registrano.com
  3. 3. ? • a.k.a Ryudo • http://www.freebbs.tw • http://www.gameckub.tw • 2007 Rails • TOMLAN FOUNDER
  4. 4. Ruby? • (interpreted) • • • Yukihiro Matsumoto, a.k.a. Matz • Lisp, Perl, Smalltalk • Happy
  5. 5. • Ruby 1.8.6 One-click Installer • http://www.ruby-lang.org/en/downloads/ • Next -> Agree -> Enable Rubygems
  6. 6. Part1:
  7. 7. irb: Interactive Ruby irb(main):001:0> irb(main):001:0> 1 + 1 => 2 irb(main):002:0> 100 * 5 + 99
  8. 8. PUTS • notepad++ hello.rb puts "Hello World!" • ruby number.rb
  9. 9. Integer 5 -205 9999999999 0
  10. 10. Float . 54.321 0.001 -12.312 0.0
  11. 11. puts 1.0 + 2.0 puts 2.0 * 3.0 puts 5.0 - 8.0 puts 9.0 / 2.0 # 3.0 # 6.0 # -3.0 # 4.5
  12. 12. puts 1 + 2 puts 2 * 3 puts 5 - 8 puts 9 / 2 # 3 # 6 # -1 # 4
  13. 13. puts 5 * (12-8) + -15 puts 98 + (59872 / (13*8)) * -52
  14. 14. String puts 'Hello, world!' puts '' puts 'Good-bye.'
  15. 15. puts 'I like ' + 'apple pie.' puts 'You're smart!' puts '12' + 12 #<TypeError: can't convert Fixnum into String>
  16. 16. Variable composer = 'Mozart' puts composer + ' was "da bomb", in his day.' composer = 'Beethoven' puts 'But I prefer ' + composer + ', personally.'
  17. 17. Conversions var1 = 2 var2 = '5' puts var1.to_s + var2 # 25 puts var1 + var2.to_i # 7 puts 9.to_f / 2 # 4.5
  18. 18. GETS puts 'Hello there, and what's your name?' name = gets.chomp puts 'Your name is ' + name + '? What a lovely name!' puts 'Pleased to meet you, ' + name + '. :)'
  19. 19. Methods • (Object) • . • self puts self.puts
  20. 20. var1 = 'stop' var2 = 'foobar' var3 = "aAbBcC" puts var1.reverse # 'pots' puts var2.length # 6 puts var3.upcase puts var3.downcase
  21. 21. Flow Control
  22. 22. puts 1 > 2 puts 1 < 2 puts 5 >= 5 puts 5 <= 4 puts 1 == 1 puts 2 != 1 puts ( 2 > 1 ) && ( 2 > 3 ) # and puts ( 2 > 1 ) || ( 2 > 3 ) # or
  23. 23. 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
  24. 24. puts "hello, who are you?" name = gets.chomp if name == "you" puts "that's you" elsif name == "me" puts "that's me" else puts "no ideas" end
  25. 25. Case case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!" end
  26. 26. command = '' while command != 'bye' puts command command = gets.chomp end puts 'Come again soon!'
  27. 27. Array a = [ 1, "cat", 3.14 ] puts a[0] # 1 puts a[1] # “cat” puts a.size # 3
  28. 28. colors = ["red", "blue"] colors.push("black") colors << "white" puts colors.join(", ") # red, blue, black, white colors.pop puts colors.last #black
  29. 29. each method languages = ['Ruby', 'Javascript', 'Perl'] languages.each do |lang| puts 'I love ' + lang + '!' end # I Love Ruby # I Love Javascript # I Love Perl
  30. 30. iterator • while each (iterator) • do .... end each ( code block)
  31. 31. 3.times do puts 'Good Job!' end # Good Job! # Good Job! # Good Job!
  32. 32. code block closure { puts "Hello" } # block do puts "Blah" # block puts "Blah" end
  33. 33. 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]
  34. 34. code block file = File.new("testfile", "r") # ... file.close File.open("testfile", "r") do |file| # ... end #
  35. 35. Hash (Associative Array) config = { "foo" => 123, "bar" => 456 } puts config["foo"] # 123
  36. 36. Symbols config = { :foo => 123, :bar => 456 } puts config[:foo] # 123
  37. 37. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  38. 38. Methods def end def say_hello(name) result = "Hi, " + name return result end puts say_hello('ihower') # Hi, ihower
  39. 39. Person Class Attributes Methods john = Person.new mary = Person.new Object Object Attributes Methods Attributes Methods
  40. 40. Classes new color_string = String.new color_string = "" # color_array = Array.new color_array = [] # color_hash = Hash.new color_hash = {} # time = Time.new puts time
  41. 41. 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
  42. 42. 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
  43. 43. 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
  44. 44. 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
  45. 45. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  46. 46. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  47. 47. class Greeter @@name = “ihower” def self.say puts @@name end end Greeter.say # Hello, ihower
  48. 48. 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
  49. 49. Part2: gem install sinatra -y --no-ri --no-rdoc gem install nokogiri -y --no-ri --no-rdoc
  50. 50. RubyGems • Ruby • gem list • http://gemcutter.org/
  51. 51. Sinatra • web development • http://www.sinatrarb.com/ • gem install sinatra
  52. 52. web app ruby myapp.rb http://localhost:4567 # myapp.rb require 'rubygems' require 'sinatra' get '/' do 'Hello world!' end
  53. 53. URL require 'rubygems' require 'sinatra' get '/hello/:name' do # "GET /hello/foo" "GET /hello/bar" # params[:name] 'foo' 'bar' "Hello #{params[:name]}!" end
  54. 54. template views hello.erb # myapp.rb require 'rubygems' require 'sinatra' get '/hello/:name' do erb :hello end
  55. 55. ERB (Ruby Template) <!DOCTYPE html> <html> <head> <title>Sinatra app</title> </head> <body> <% 10.times do %> <p><%= "Hello #{params[:name]}!" %></p> <% end %> </body> </html>
  56. 56. Template # myapp.rb require 'rubygems' require 'sinatra' get '/array' do @arr = ["aaa","bbb","ccc","ddd"] erb :array end # views/array.erb <% @arr.each do |item| %> <p><%= item %></p> <% end %>
  57. 57. # myapp.rb # views/index.erb require 'rubygems' <form action="/query" method="post"> require 'sinatra' <p><input type="text" name="keyword" value=""></p> get '/' do <p><input type="submit" value="Submit"></p> erb :index end </form> post '/query' do params[:keyword] end
  58. 58. nokogiri • HTML, XML, SAX (parser) • XPath CSS • gem install nokogiri
  59. 59. require 'rubygems' require 'nokogiri' text = "<html> <ul> <li>FOOOBARRR</li> <li>AAAAACCCCC</li> <ul> </html>" doc = Nokogiri::HTML(text) puts doc.css('li').size # 2 doc.css('li').each do |item| puts item.content end # FOOOBARRR # AAAAACCCCC
  60. 60. sinatra+nokogiri # myapp.rb require 'rubygems' require 'sinatra' require 'nokogiri' require 'open-uri' get '/' do erb :index end post '/query' do html = open( params[:keyword] ).read doc = Nokogiri::HTML(html) @links = doc.css('a') erb :query end
  61. 61. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <ul> <% @links.each do |link| %> <li> <%= link.content %> <%= link.attributes["href"] %> </li> <% end %> </ul> </body>
  62. 62. Thank you. Learn to Program http://pine.fm/LearnToProgram/ Beginning Ruby 2nd. (Apress)
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×