簡體   English   中英

調用 ruby class 方法和存儲在proc中的參數

[英]Call ruby class method and parameters stored in proc

我有一個proc設置如下:

@method_to_call = Proc.new { || {:method=>'some_method',:user_id=>1 } }

現在我想用參數user_id調用方法some_method

def some_method(user_id)
 # does something
end

關鍵是 proc 還可以有不同的參數,例如:

@method_to_call = Proc.new { || {:method=>'some_method_two',:user_id=>1, :app_id=>2 } }

哪個會調用:

def some_method_two(user_id,app_id)
  # do something
end

我目前有一個如圖所示的方法:

def handle_action
  parts = @method_to_call.call
  curr_method = parts[:method]
  if curr_method == "some_method"
     some_method parts[:user_id]
  elsif curr_method == "some_method_two"
     some_method_two parts[:user_id], parts[:app_id]
  end
end

但我想要類似...

def handle_action
   # call method in proc and pass parameters stored in proc dynamically
end

如果您將 procs 構造為方法名稱和參數列表:

Proc.new { ['some_method', [1]] }
Proc.new { ['some_method_two', [1, 2]] }

然后你可以做

def handle_action
  method, args = @method_to_call.call

  public_send(method, *args)
end

如果這會損害理解(鑒於user_idapp_id不再記錄),您始終可以將這些方法轉換為使用關鍵字 arguments,然后重寫為

def some_method_two(user_id:, app_id:)
  do_something
end

@method_to_call = Proc.new { ['some_method_two', { user_id: 1, app_id: 2 }] }

def handle_action
  method, args = @method_to_call.call

  public_send(method, **args)
end

出於興趣,您是否有任何理由首先需要使用 procs? 是否需要延遲對方法 arguments 的評估?

接受的答案已經顯示了可能的情況。 我只想分享你也可以從 Proc 內部調用方法。

@method_to_call = Proc.new do |**kwargs|
  some_method(kwargs.except(:method)) if kwargs[:method] == 'some_method'
  some_method_2(kwargs.except(:method)) if kwargs[:method] == 'some_method_2'
end

def some_method(user_id:)
  puts "User ID: #{user_id}"
end

def some_method_2(user_id:, app_id:)
  puts "User ID: #{user_id}, App ID: #{app_id}"
end

@method_to_call.call({ method: 'some_method', user_id: 1 })
@method_to_call.call({ method: 'some_method_2', user_id: 1, app_id: 2 })

Output:

User ID: 1
User ID: 1, App ID: 2

請注意: Hash#except方法在 Rails 中可用,最近 Ruby 從Ruby 3.00開始也支持此方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM