英文:
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("Net::HTTP::#{restVerb}")
=> Net::HTTP::Post
klass.new(uri)
=> #<Net::HTTP::Post POST>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论