在 Ruby 中将类对象转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12347213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Class Object to string in Ruby
提问by Anil D
I m in a situation where i need to convert an Object to string so that i can check for Invalid characters/HTML in any filed of that object.
我处于需要将对象转换为字符串的情况,以便我可以检查该对象的任何字段中的无效字符/HTML。
Here is my function for spam check
这是我的垃圾邮件检查功能
def seems_spam?(str)
flag = str.match(/<.*>/m) || str.match(/http/) || str.match(/href=/)
Rails.logger.info "** was spam #{flag}"
flag
end
This method use a string and look for wrong data but i don't know how to convert an object to string and pass to this method. I tried this
此方法使用字符串并查找错误数据,但我不知道如何将对象转换为字符串并传递给此方法。我试过这个
@request = Request
spam = seems_spam?(@request.to_s)
Please guide
请指导
Thanks
谢谢
回答by kits
You could try @request.inspect
你可以试试 @request.inspect
That will show fields that are publicly accessible
这将显示可公开访问的字段
Edit: So are you trying to validate each field on the object?
编辑:那么您是否尝试验证对象上的每个字段?
If so, you could get a hash of field and value pairs and pass each one to your method.
如果是这样,您可以获得字段和值对的散列并将每一个传递给您的方法。
@request.instance_values.each do |field, val|
if seems_spam? val
# handle spam
end
If you're asking about implementing a to_s method, Eugene has answered it.
如果您要问实施 to_s 方法,Eugene 已经回答了。
回答by Eugene Dorian
You need to create "to_s" method inside your Object class, where you will cycle through all fields of the object and collecting them into one string.
您需要在 Object 类中创建“to_s”方法,您将在其中循环遍历对象的所有字段并将它们收集到一个字符串中。
It will look something like this:
它看起来像这样:
def to_s
attributes.each_with_object("") do |attribute, result|
result << "#{attribute[1].to_s} "
end
end
attribute variable is an array with name of the field and value of the field - [id, 1]
属性变量是一个包含字段名称和字段值的数组 - [id, 1]
Calling @object.to_swill result with a string like "100 555-2342 machete "which you can check for spam.
调用@object.to_s将产生一个字符串"100 555-2342 machete ",您可以通过该字符串检查是否存在垃圾邮件。

