Ruby how to use method parameter embedded in call to another method other than just puts

huangapple go评论54阅读模式
英文:

Ruby how to use method parameter embedded in call to another method other than just puts

问题

在Ruby中,我想在调用Net::HTTP的new方法时使用一个输入参数来表示REST动词(比如'Post'),但我不知道如何将这个参数嵌入语句中。我有一个名为restVerb的参数,它在puts "Verb is #{restVerb}"中打印出来没有问题,但在request = Net::HTTP::#{restVerb}.new(uri)中不起作用 - 我得到了undefined method 'request' for Net::HTTP:Class (NoMethodError),所以显然它没有识别语句中参数的值。我可以使用case语句,但我想使它更通用。我做错了什么?

我尝试过上述语法以及其他一些,比如request = Net::HTTP::restVerb.new(uri)request = Net::HTTP::$restVerb.new(uri),我对Ruby还不太熟悉,请对我宽容一些。

英文:

In Ruby I want to use an input parameter for REST verb (like 'Post') in a call to Net::HTTP new but I can't work out how to embed the parameter in the statement. I have the param called restVerb which prints fine in puts "Verb is #{restVerb}" but not in request = Net::HTTP::#{restVerb}.new(uri) - I get undefined method request' for Net::HTTP:Class (NoMethodError)` so it clearly doesn't recognise the parameter's value in the statement. I could use a case statement but wanted to make it more generic. What am I doing wrong?

I've tried the above syntax and a few others like request = Net::HTTP::restVerb.new(uri) or request = Net::HTTP::$restVerb.new(uri) I'm new to Ruby so be gentle with me please.

答案1

得分: 1

使用 Object.const_get 将字符串转换为实际常量:

klass = Object.const_get("Net::HTTP::#{restVerb}")
=> Net::HTTP::Post

klass.new(uri)
=> #<Net::HTTP::Post POST>
英文:

Use Object.const_get to convert a string to an actual constant:

klass = Object.const_get(&quot;Net::HTTP::#{restVerb}&quot;)
=&gt; Net::HTTP::Post

klass.new(uri)
=&gt; #&lt;Net::HTTP::Post POST&gt;

huangapple
  • 本文由 发表于 2023年2月9日 00:41:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定