2012-09-20

reading notes of Programming Ruby 2nd





a.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
animals = %w{ant bee cat dog elk}
def say_hello (name)
  "Hello, #{name.capitalize}"
end

puts say_hello('ww')

$globalV = "hello"
@instanceV = "instanceV"
@@classV = "ww"
puts "#$globalV, #@instanceV #@@classV"



hash_example = {
  'a' => 'A',
  'b' => 'B',
  'c' => 'C'
}
puts hash_example['c']

hash_default_value_zero = Hash.new(0)
puts hash_default_value_zero['key-do-not-exists'] == 0

testflag = true
puts "use simple if statement, if possible" if testflag

puts "regex demo: if perl match /perl|python/" if "perl" =~ /perl|python/

aline = 'Perl and Python'
aline.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' 
aline.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'
aline.gsub(/Perl|Python/, 'Ruby')

animals.each { |animal| puts animal }
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }

class Song
  attr_reader :name, :artist, :duration, :attr_foo
  attr_writer :name, :artist, :duration
  protected :attr_foo

  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
  
  def to_s
    "Song: #@name, #@artist, #@duration "
  end
end

class SubSong < Song
  CONSTANTS_START_WITH_UPPERCASE_LETTER = 300
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end  

  def SubSong.staticMethod
    "static method"
  end

  def [] (seconds)  #index method, e.g: SubSong[22]
    seconds
  end

  def play
  end

  def pause
  end

  def inspect
    '#' * 10
  end
end

s = SubSong.new("a", "b", "c", "lyrics")
puts
puts s.duration
puts s.name
puts SubSong.staticMethod

class SingletonLogger
  private_class_method :new
  @@logger = nil
  def SingletonLogger.get_instance
    @@logger = new unless @@logger
    @@logger
  end

  def self.static_method_form_b
  end
  
  class << self
    def static_method_form_c
    end
  end

  def public_method_a
  end
  public :public_method_a

  protected
    def protected_method_a
    end
  private
    def private_method_a
    end
end

i = SingletonLogger.get_instance
puts i.object_id == SingletonLogger.get_instance.object_id
puts i.class
j = i.dup   #duplicate a new object
puts j.class
j.freeze    #freeze an object

array = Array.new
array[0] = "xxx"
array[1] = "yyy"
array[2] = "zzz"
puts array[0,2]
puts array[100] == nil

#a=[1,3,5,7,9]    → [1,3,5,7,9]                        
#a[2, 2] = ’cat’   → [1, 3, "cat", 9]                   
#a[2, 0] = ’dog’   → [1, 3, "dog", "cat", 9]            
#a[1,1]=[9,8,7]   → [1,9,8,7,"dog","cat",9]            
#a[0..3] = []     → ["dog", "cat", 9]                  
#a[5..6] = 99, 98 → ["dog", "cat", 9, nil, nil, 99, 98]



require 'test/unit'
class TestSong < Test::Unit::TestCase
  def test_method
    h = { 'a' => 'A', 'b' => 'B', 'c' => 'C'}
    assert_equal(h['c'], 'C')
  end
end


def two_times
  yield
  yield
end

two_times { puts "Hello"}

a = [1, 'cat', 3.14]   #array with three elements
a[2] = nil
puts a.find {|element| element == 1}
puts [1,3,5,7,9].find{|v|v*v>30}
puts [1,3,5,7,9].each {|i| puts i}
puts ['S', 'V'].collect {|x| x.succ}
puts defined?(not_defined_variable) == nil

puts [1,2,3,4].inject {|p, e| p*e}

class File
  def File.with_file_open(*args)
    result = f = File.open(*args)
    if block_given?
      result = yield f
      f.close
    end
    f
  end
end

song = SubSong.new("a", "b", "c", "d")
p s
class SongButton
  def initialize(label, &action)
    @label = label
    @action = action
  end

  def button_pressed
    @action.call(self)
  end
end

start_button = SongButton.new("Start") { song.start }

def n_times(thing)
  return lambda { |n| thing *n }
end

proc_3_times = n_times("hello")
puts proc_3_times.call(3)

num = 81
5.times do 
  puts "#{num.class}: #{num}"
  num *= num
end

99.downto(96) { |i| print i, " " }
50.step(80,5) { |i| print i, " " }

puts "#{'hello ' * 3}"
puts "now is #{
def the(a)
  'the ' + a
end
the('time')
} for all.."

p (1..10).to_a
p ('bar'..'bat').to_a

digits = 0..9
puts digits.include?(5)

puts 1 <=> 2
puts 1 <=> 1

puts (1..10) === 5
puts (1..10) === 12

#102 More about methods
#method name instance_of? chop chop! name=

def method_without_parameters_do_not_need_parenthesis
puts ' '
end

def method_parameter_can_have_default_value(input="hello")
puts input
end
method_parameter_can_have_default_value

def varargs(arg1, *rest)
  "Got #{arg1} and #{rest.join(', ')}"
end

puts varargs("first variable", "and", "more", "params")

#if block_given?

#if omit the receiver, it defaults to self.
#self.frozen?  is same as frozen?
#self.id       is same as id

#Modules
module Module_Can_do_mixin
  PI = 3.14
  def morsecode
  end
end

module Debug
  def who_am_i
    "#{self.class.name}"
  end
end

class Photo
  include Debug
end

require 'open-uri'
open('http://www.sina.com.cn') do |f|
  puts f.read.scan(/<img src="(.*?)"/m).uniq
end

#Threads and Processes
#P377 to be continue...

No comments:

Post a Comment