Ruby => operator... eg: :text => /Log In/
What does this do? I find the example here, but other than what it does, what does it mean? I can't find anything on开发者_开发知识库 google because well, I am not sure what '=>' is even called in this context.
More examples here: http://mechanize.rubyforge.org/mechanize/EXAMPLES_rdoc.html
In :text => /Log In/
, you are passing a hash to page
's link_with
function, and the key in the hash is :text
and its corresponding value is /Log In/
.
Basically: :x => y
means that :x
is a key in a hash that maps to a value of y
.
passing hashes to functions like this allows you to have something like (but not exactly) named parameters.
UPDATE:
A symbol of the form :something
is called.... a symbol! You can think of them sort of like global string constants (but they're not quite the same). Now, when you think back to something like:
login_page.form_with(:action => '/account/login.php')
What you're actually doing is constructing a new hash on the fly. You create a new element in the hash, where the key is a string with the value "action", and the value of that element is "/account/login.php" (in this case, also a string, but I'm pretty sure you can store other things in hashes besides strings).
...whew! It's been a while since I've worked with Ruby. I hope I got that all correct. ;)
Some good looking pages here (more can be found by searching google for "ruby symbol")
http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols
http://www.troubleshooters.com/codecorn/ruby/symbols.htm#_What_are_symbols
It associates a value with an index for hashes.
obj.method :text => /Log In/
is shorthand for
obj.method {:text => /Log In/}
It's used to create a hash expression, as in { key => value }
.
Also, when used as the last parameter in a method call, the { }
are not needed, so the key => value
can appear alone.
>> p({:a => 1, :b => 2})
{:a=>1, :b=>2}
=> nil
>> p :c=>3, :d=>4
{:d=>4, :c=>3}
=> nil
>> t = { :e=>5, :f=>6 }
=> {:f=>6, :e=>5}
This shorthand is really nice in poetry mode, where a literal hash following a method name would look like a block.
精彩评论