Top Page > Ruby �����W > ���l�^��


Ruby �����W ���l�^��


���p���͂Ȃ��i�Ǝv���j�l�^�n���C�u�����B�ڂ��ڂ��lj��\��B


dispatch

�\�[�X: dispatch.rb

�����^�ɂ�郁�\�b�h�I�[�o���[�h���ł���悤�ɂ��郉�C�u�����BRuby�̕��@���ő���Ɉ��p�����A����ȍ\���������B

  def hoge(*args)
    dispatch(args).
      when(Integer) do |i|
        printf("Integer %d\n", i)
      end.
      when(String) do |s|
        printf("String %s\n", s)
      end.
      when(String, Integer) do |s, i|
        printf("String %s and Integer %d\n", s, i)
      end.
    end
  end
  
  hoge(3)
  hoge("s")
  hoge("t", 4)

StrongTyping�������Ƃ܂��Ƃ��ȍ\���œ��������������Ă�̂ŁA�g���Ȃ炱����������߂��܂��i�΁j�B


product

�\�[�X: product.rb

�N���X�̑g�iproduct�j�ɑ΂��ă��\�b�h���`�ł���悤�ɂ��郉�C�u�����B

�Ⴆ�Έȉ��ł́AAcid�N���X��Base�N���X�̑g�ɑ΂��āAsalt�Ƃ������\�b�h���`���Ă��܂��B

  class Acid
      include(Producable)
      attr_accessor(:anion)
  end
  
  class Base
      include(Producable)
      attr_accessor(:cation)
  end
  
  def_product(Acid*Base) do
      def salt
        return rhs.cation + lhs.anion
      end
  end

�g���Ƃ��͂���Ȋ����B

  h_cl= Acid.new()
  h_cl.anion= "Cl"
  na_oh= Base.new()
  na_oh.cation= "Na"
  
  p (h_cl*na_oh).salt    # => "NaCl"
  p (h_cl*na_oh).class   # => Acid*Base

�ꉞ�A���̃N���X�̌p���֌W�����f����܂��B

  class WeakBase < Base
  end
  
  def_product(Acid*WeakBase) do
      def acid?
        return true
      end
  end
  
  nh4_oh= WeakBase.new()
  nh4_oh.cation= "NH4"
  
  p (h_cl*nh4_oh).salt               # => "NH4Cl"
  p (h_cl*nh4_oh).acid?              # => true
  p (h_cl*nh4_oh).is_a?(Acid*Base)   # => true

�����A���̌p���ɂ͐F�X�������L���āA�Ⴆ�΁AAcid*Base���O��Acid*WeakBase���`���Ă��܂��ƁA�ςɂȂ�܂��B���ƁARuby�ł͑��d�p�����ł��Ȃ��̂ŁA���N���X��₪��������悤�ȏ󋵂ł́A�����ɋ��ʂ̊��N���X���A���N���X�ɂȂ�܂��i�킯�킩���j�B

�������AArray�Ȃǂ̊����̃N���X��product����`�ł��܂��B�����A*���Z�q���ƏՓ˂���̂ŁA����������Ɖ����ȁi�H�jproduct�Ƃ����֐����p�ӂ��܂����B

  def_product(Array*Array) do
      def map(&block)
        return (0...lhs.size).map(){ |i| yield(lhs[i], rhs[i]) }
      end
  end
  
  p product([1, 2], [3, 4]).map(){ |a, b| a+b }   # => [4, 6]

3�ˆȏ��product�́A�uproduct��product�v�Ƃ��Ē�`�ł��܂��B

  def_product(Object*Symbol*Array) do
      def call()
        obj= lhs.lhs
        sym= lhs.rhs
        ary= rhs
        obj.send(sym, *ary)
      end
  end
  
  p product("hoge", :gsub, [/o/, "e"]).call()   # => "hege"

O/R�}�b�p�݂����Ȃ��̂��l���ĂāA�����e�[�u���ɕR�Â��e�[�u�����ăI�u�W�F�N�g�ł͂ǂ������񂾂낤�Ǝv���āA�v���‚������́B


���l�^�� < Ruby �����W < TopPage