Skip to content

Instantly share code, notes, and snippets.

@ilake
Last active October 20, 2015 18:41
Show Gist options
  • Select an option

  • Save ilake/d63248c8026bc38dad57 to your computer and use it in GitHub Desktop.

Select an option

Save ilake/d63248c8026bc38dad57 to your computer and use it in GitHub Desktop.

to_int

These are used all over the place within Ruby, but as an example #to_int is used to convert the argument to Array#[] to an int, and #to_str is used by raise when its argument isn’t an Exception.

class Line
  def initialize(id)
    @id = id
  end
  def to_int
    @id
  end
end

line = Line.new(2)
names = ["Central", "Circle", "District"]
names[line]   #=> "District"

unary &

& converts a Proc object into a block argument in a method call.

sum = Proc.new {|a, b| a + b}
(1..10).inject(&sum)   #=> 55
class Point
  attr_accessor :x, :y
  def initialize(x, y)
    @x, @y = x, y
  end

  def self.to_proc
    Proc.new {|ary| new(*ary)}
  end
end

[[1, 5], [4, 2]].map(&Point)   #=> [#<Point:0x007f87e983af40 @x=1, @y=5>, #<Point:0x007f87e983ace8 @x=4, @y=2>]

Exception

module MyProject
  class Error < StandardError
  end

  class NotFoundError < Error
  end

  def get
    uri = URI('http://examp.cm/500')
    response = Net::HTTP.get_response(uri)
    raise NotFoundError, "#{uri} not found" if response.code == "404"
    p response.body
  rescue SocketError => e
    raise e
  end
end

class T
  include MyProject

  def test_get
    begin
      get
    rescue MyProject::Error => e
      p e 
    rescue => e
      p e  # Then you will get exeption here 
    end
  end
end

But if you

module MyProject
  Error = Module.new

  class NotFoundError < StandardError
    include Error
  end

  def get
    uri = URI('http://examp.cm/500')
    response = Net::HTTP.get_response(uri)
    raise NotFoundError, "#{uri} not found" if response.code == "404"
    p response.body
  rescue SocketError => e
    e.extend(Error)
    raise e
  end
end

class T
  include MyProject

  def test_get
    begin
      get
    rescue MyProject::Error => e
      p e # Then you could get exception from here, we know where it come from MyProject::NotFoundError or SocketError
    end
  end
end

module

module T
  module_function

  def t
    p 'ttt'
  end
end

module A
  extend self

  def a
    p 'aaa'
  end
end

T.t # ttt
A.a # aaa

Find Files

config_path = File.expand_path("config.yml", __dir__)

const_get

klass = Object.const_get(string)

RBTree http://rbtree.rubyforge.org/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment