Rubyのあれこれ、
あれこれ
普段Rubyを触っていてこれは学びとして記録しておきたいなと思ったものを紹介していきます。
OpenStruct
Rubyには手軽に構造体を作成することができるOpenStructクラスが用意されています。
require 'ostruct' ab = OpenStruct.new ab.foo = 25 p ab.foo # => 25 ab.bar = 2 p ab.bar # => 2 p ab # => <OpenStruct foo=25, bar=2> ab.delete_field("foo") p ab.foo # => nil p ab # => <OpenStruct bar=2>
使いたい場合には require 'ostruct' で宣言をします。
ab.foo = 25
このように要素に値をセットしていきます。
OptionParser
コマンドラインのオプションを扱うためのライブラリ
require 'optparse' opt = OptionParser.new opt.on('-a') {|v| p v } opt.on('-b') {|v| p v } opt.parse!(ARGV) p ARGV ruby sample.rb -a foo bar -b baz # => true true ["foo", "bar", "baz"]
require 'optparse' で宣言を行う
OptionParserクラスのインスタンスを作成し、
インスタンスに引数があった場合の動きを定義します。
parseメソッドが呼ばれた時に、コマンドラインにオプションが指定されていればそのオプションの動きが実行される。
NoImplementedError
Rubyでプログラムを実装する際にovverrideすることを強制するためにNoImplementErrorを強制的に呼び出す方法。
Baseクラスに主機能をまとめておき、それを継承する形で子classを実装する。
子クラスのインスタンスでメソッドを呼び出した際に、overrideで実装されていなければエラーが起きるように親クラスにNoImprementedErrorを定義する。
class Pokemon attr_reder :name def initialize(name) @name = name end def show "#{name} は #{revel} レベルで #{type} タイプだ!" end private # サブクラスで必ず実装する def revel raise NotImprementedError.new("You must implement #{self.class}##{__method__}") end def type raise NotImprementedError.new("You must implement #{self.class}##{__method__}") end end class Hushigidane < Pokemon private def level "5" end end class Zenigame < Pokemon private def type "みず" end end class Hitokage < Pokemon private def level "12" end def type "火" end end Hushigidane.new("フシギダネ").show #=> NotImplementedError: You must implement Hushigidane#type Zenigame.new("ゼニガメ").show #=> NotImplementedError: You must implement Zenigame#level Hitokage.new("ヒトカゲ").show #=> "ヒトカゲ は 12 レベルで 火 タイプだ!"