Ruby 复习课

下面整理自 The Ruby Way by Hal Fulton(陈秋萍、赵子鹏所译)初章,我选取了一些典型的,能体现 Ruby 设计思想的代码作为 Ruby 复习内容。


参考:

  1. The Ruby Way by Hal Fulton
### THE RUBY WAY - Hal Fulton

count = 0

count += 1
puts "No.#{count} Loop & Condition"

list = %w/alpha bravo charlie delata echo/

# Loop 1(while)
i = 0
while i < list.size do
  print "#{list[i]} "
  i += 1
end
puts

# Loop 2(until)
i = 0
until i === list.size do
  print "#{list[i]} "
  i += 1
end
puts

# Loop 3(for)
for x in list do
  print "#{x} "
end
puts

# Loop 4('each' iterator)
list.each do |x|
  print "#{x} "
end
puts

N = list.size

# Loop 5('loop' method)
i = 0
loop do
  print "#{list[i]} "
  i += 1
  break if i > N - 1
end
puts

# Loop 6('loop' method)
# NOTE 'loop' is a kernal method, not key words
i = 0
loop do
  print "#{list[i]} "
  i += 1
  break unless i <= N - 1
end
puts

# Loop 7('times' iterator)
N.times do |i|
  print "#{list[i]} "
end
puts

# Loop 8('upto' iterator)
0.upto(N - 1) do |i|
  print "#{list[i]} "
end
puts

# Loop 9(for)
for i in 0...N do
  print "#{list[i]} "
end
puts

# Loop 10(each_index)
list.each_index do |i|
  print "#{list[i]} "
end
puts


puts
count += 1
puts "No.#{count} Generator"

def my_sequence
  for i in 1..10 do
    yield i
  end
end

my_sequence {|x| puts x ** 3 }

puts
count += 1
puts "No.#{count} Exception"

# Rescue 1
begin
  # ....
  raise ArgumentError.new('Error')
rescue ArgumentError => e
  # ...
rescue ZeroDivisionError => e
  # ...
end

# Rescue 2
begin
  # ...
  fail ZeroDivisionError.new 'Error'
rescue => err
  # ...
end

# rescue 3
begin
  # ...
rescue ZeroDivisionError => e
  # ...
else
  # Other exception
end

# rescue 4(retry)
begin
  # ...
rescue  => err
  # ...
  retry
end

# rescue 5(ensure)
begin
  # ...
rescue  => err
  # ...
ensure
  # ...
end

# rescue 6
x = 2 / 0 rescue puts('Division by zero!')

# rescue 7(Implicit)
def some_method
  # Code
rescue
  # Recovery
end


puts
count += 1
puts "No.#{count} OOP"

1.succ
''.object_id
%w/4 2 3 1/.map(&:to_i).sort

x = 'abc'
x.gsub! /a/, 'x'
x.freeze    # const

# Class
class MyClass

  NAME = 'Class Name' # class constant
  @@myname = '严文' # class variable

  @class_instance_val = ''

  def initialize name, sex, phone
    @name, @sex, @phone = name, sex, phone
  end

  def name
    @name
  end

  def name= name
    @name = name
  end

  def sex
    @sex
  end

  def phone
    @phone
  end

  # using symbols
  private :name, :name=
  protected :sex
  
  # attr_reader
  # attr_writer
  attr_accessor :phone

  # class method
  def self.myname
    @@myname
  end

  # or
  class << self
    def yet_another_myname
      @myname
    end
  end

  # public (below)
  public

  def say_hello
    puts "Hello #{@@myname}"
  end

  # alias
  alias say_me say_hello
end

# singleton class
str = 'hello'
class << str
  def hyphenated
    self.split(//).join '-'
  end
end
puts str.hyphenated

# multiple args
def mymethod a, b, *c
  print "#{a} #{b} "
  c.each { |x| print "#{x} " }
  puts
end
mymethod 2, 3, 4, 1

# singleton method
str = 'Hello, world!'
def str.spell
  self.split(//).join '-'
end
puts str.spell

def nil.+ other
  other
end
puts nil + str

# reflaction
defined? variable

''.class

1.is_a? 2.class
1.kind_of? 2.class

2.methods
3.private_methods

Object.superclass

ObjectSpace._id2ref 1.object_id
ObjectSpace.each_object

if $0 == __FILE__
  puts 'Not library'
end

puts
count += 1
puts "No.#{count} Functional"

# Closure
def power exponent
  proc { |base| base ** exponent }
end

square = power 2
cube = power 3

puts square.call 11
puts cube.call 20

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s