3
def wait_for_element_present(element)
    wait = Selenium::WebDriver::Wait.new(:timeout => 30);
    wait.until{driver.find_element(element)};
end

Please take a look at the Ruby code above, I have two questions:

(1) As for "Selenium::WebDriver::Wait.new(:timeout => 30)", what does the "=>" mean here? I know ":timeout" is a ruby symbol, but when using it following by a "=>" and a value "30", I get confused. Is this some kind of trick about ruby symbol?

(2) We also have the symbol "=>" when defining hash right? Like:

cars = {
'altima' => 'nissan',
'camry' => 'toyota',
'rx7' => 'mazda'
}
puts cars['rx7']   =>   mazda

Does the "=>" here has the same meaning as that in question (1)?

I'm a ruby newbie, any comments would be appreciated. Thanks in advance!

0

2 Answers 2

5

Yes, it has the same meaning. In both cases, it's definition of a hash. Ruby allows to omit curly braces of hash literal, if it is the last parameter in method's signature.

Example:

def my_method a, b, h
  puts a
  puts b
  puts h
end


my_method(1, 2, :timeout => 30)
# my_method(1, 2, timeout: 30) # alternative syntax for ruby 1.9+
# >> 1
# >> 2
# >> {:timeout=>30}

Note that it only works for last parameter which is hash. If you have several hashes at the end, you have to use normal form (with curly braces) for all but the last.

4
  • I found something interesting here: stackoverflow.com/questions/969900/…. In the second answer, it says, "Rails, and other Ruby code, often pass hashes as parameters to methods to achieve the same effect as named arguments in other languages like Python." So it is the same usage here as named arguments right? There's a parameter named "timeout" for the constructor of Selenium::WebDriver::Wait right?
    – Bruce Sun
    Commented Aug 30, 2012 at 1:02
  • Thanks, Sergio, I really appreciate your help, and also others' answers. Ruby is so different from C# that I start to realize that I can't bring too much C# thinking with me into Ruby learning.
    – Bruce Sun
    Commented Aug 31, 2012 at 1:04
  • Ruby 2 will have real named parameters. Does C# have them already (it's been a while since I touched it)? Commented Aug 31, 2012 at 5:00
  • Yes, we have it since C#.NET 4.0
    – Bruce Sun
    Commented Aug 31, 2012 at 12:42
1
Selenium::WebDriver::Wait.new(:timeout => 30)

is shorthand for

Selenium::WebDriver::Wait.new({:timeout => 30}) 

It takes a hash in its argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.