美文网首页
ruby 常用核心库

ruby 常用核心库

作者: RickyWu585 | 来源:发表于2023-01-08 09:18 被阅读0次

Exception Handling:

  • how to raise an Exception:
def foo
  raise 'error' // Runtime Exception
end

def bar 
  raise ArgumentError, 'error msg', caller
end
  • how to handle an Exception:
begin 
  ...
  rescue ArgumentError => e
  ...
  rescue TypeError => e
  ...
  else // 上面的错误没发生,走这里
  ...
  ensure // whether the exceptions occur,it will run
  ...
end
  • example:
def factorial n
  raise TypeError unless n.is_a? Integer
  raise ArgumentError if n < 1
  return 1 if n == 1
  n * factorial(n-1)
end

begin
  x = factorial -1
  rescue ArgumentError => e
    p 'Try again with a value >= 1'
  rescue TypeError => e
    p 'Try again with an integer'
  else
    p x
  ensure
    p 'The process of factorial calculation is completed'
end
arr = [1,2,'a',3,'hello',world]

def sum_pair
  sum = 0
  arr.each_slice(2) do |pair|
    begin 
      p pair[0] + pair[1]
      rescue TypeError => e
        p "Invalid summation of #{pair[0].class} + #{pair[1].class}"
      ensure
        sum += 1
    end
  end
  p "There are #{sum} pairs processed"
end

Enumerable and Comparable:Array/Hash; String/Integer都是因为include了这两模块中的一个变的强大

  • Enumerable
    1673082922862.png
  • Comparable
Comparable.instance_methods :
[:clamp, :<=, :>=, :==, :<, :>, :between?]
  • 自定义实现可Enumerable 和Comparable的class:
class Person
  attr_reader :name
  include Comparable
  
  def initialize name
    @name = name
  end

  def <=> other
    self.name <=> other.name
  end
end

p1 = Person.new 'frank'
p2 = Person.new 'ricky'
p3 = Person.new 'ant'

p1 < p2
p2.between? p1, p3

------------------------------

class People 
  attr_reader :people

  def initialize people
     @people = people
  end

  def each
    raise 'please provide a block!' unless block_given?
    people.each do |person|
      yield person
    end
  end
end

people = People.new [p1,p2,p3]

people.each {|person| p person.name}
people.detect {|person| person.name == 'ricky'}

Regex

Time ,Date and DateTime

  • Date is a standard lib,which needs be reqiured;Time is a core lib
  • DateTime < Date;Time, Both Three classes include Comparable module
  • create date and date time:
// require 'date'
require 'time' // 会将 Date 以及 DateTime 都 load,一般情况下用这个就行

date = Date.today
DateTime.now
Time.now

date.year
date.month
date.day
date.wday // week day
date.prev_day

date + 1

项目级别常用命令

// bundle:管理gems关系的gem 包
bundle init
bundle exec ...
bundle install/update/show/list

gem list
gem install
gem uninstall
gem sources

// 新建项目:
bundle init // 生成Gemfile 
vim Gemfile // 修改 gems 信息
bundle // 安装对应 gems

// 创建 gems 项目:
bundle gem xxx

相关文章

网友评论

      本文标题:ruby 常用核心库

      本文链接:https://www.haomeiwen.com/subject/iovscdtx.html