简体   繁体   English

如何在Ruby中转义符号(不是字符串)

[英]How to escape a symbol (not string) in Ruby

I'm creating a web crawler with Ruby and Mechanize. 我正在使用Ruby和Mechanize创建一个Web爬虫。 The web site that I'm crawling is sending this kind of POST data with square brackets. 我正在抓取的网站正在发送带有方括号的这种POST数据。 The problem is that Mechanize uses struct and I haven't found a way to escape the square brackets in a struct key: 问题是Mechanize使用struct而我还没有找到一种方法来转义结构键中的方括号:

   post_body = {
       data[User][username]: username,
       data[User][password]: password,
       data[selector]: 1
   } 

I've tried to put the keys inside strings, and to use this kind of syntax: 我试图将键放在字符串中,并使用这种语法:

post_body = Struct.new(#{data[User][username]}, #{data[User][password]}, #{data[selector]})
post_body.new(username, password, 1)

but I get an error: 但是我收到一个错误:

identifier data[User][username] needs to be constant

To make what @ndenkov already said more explicit: 为了使@ndenkov已经说得更明确:

If you have a hash 如果你有哈希

{ foo: 4711 }

this is just syntactic sugar for 这只是语法糖

{ :foo => 4711 }

This means that the key must syntactically be a simple symbol, basically following the same syntax as an identifier. 这意味着键必须在语法上是一个简单的符号,基本上遵循与标识符相同的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM