0

最近、Ruby on Rails でプロジェクトを開始しました。以前はすべてのプロジェクトを Python で行っていましたが、Ruby を試してみることにしました。

私が Python で書いたプロジェクトでは、この投稿の正解で説明されているちょっとしたテクニックを使用しました。

辞書または If ステートメント、Jython

Python にはネイティブなスイッチ機能がなく、大きな if else ブロックも取り除くため、私はこの手法を使用します。

Rubyで上記のメソッドを再作成しようとしていますが、完全に取得できないようです。

誰か助けてくれませんか?

4

3 に答える 3

2

クラスベースのアプローチを使用することを妨げるものは何もありませんが、なぜ ruby​​scaseステートメントを避けるのでしょうか?

case thing
when 'something'
   do_something
when 'nothing'
   do_nothing
else
   do_fail
end
于 2010-04-02T11:04:51.427 に答える
2

文字列に格納された名前だけでメソッドを呼び出す必要がある場合、Ruby の標準的な方法は method を使用することですObject#send

def extractTitle dom
  puts "title from #{dom}"
end

def extractMetaTags dom
  puts "metatags from #{dom}"
end

dom = 'foo'

type = 'extractTitle'
send type, dom
#=> title from foo
type = 'extractMetaTags'
send type, dom
#=> metatags from foo

それ以外の場合は、既に提案されているように、Ruby のcaseステートメントを使用できます。

于 2010-04-02T11:06:02.180 に答える
1

他の人が言ったように、Ruby でこれを行う別の方法がありますが、興味がある場合は、Ruby での Python アプローチ (メソッド名を決定したらObject#sendを使用する) に相当するものは次のようになります。

class MyHandler
  def handle_test(arg)
    puts "handle_test called with #{arg}"
  end

  def handle_other(arg)
    puts "handle_other called with #{arg}"
  end

  def handle(type, *args)
    method_name = "handle_#{type}"
    if respond_to? method_name
      send(method_name, args)
    else
      raise "No handler method for #{type}"
    end
  end
end

その後、次のことができます。

h = MyHandler.new
h.handle 'test', 'example'
h.handle 'other', 'example'
h.handle 'missing', 'example'

出力は次のようになります。

handle_test called with example
handle_other called with example
handle.rb:15:in `handle': No handler method for missing (RuntimeError)
        from handle.rb:23
于 2010-04-02T11:14:26.320 に答える