Thursday, January 20, 2011

Web Application Testing in Ruby: Ruby scripting Basic

Web Application Testing in Ruby: Ruby scripting Basic

A Difference Between {} and do/end
As mentioned, there's one small difference between brace enclosed blocks and do/end enclosed blocks: Braces bind tighter. Watch this:
#!/usr/bin/ruby
my_array = ["alpha", "beta", "gamma"]
puts my_array.collect {
|word|
word.capitalize
}
puts "======================"
puts my_array.collect do
|word|
word.capitalize
end
[slitt@mydesk slitt]$ ./test.rb
Alpha
Beta
Gamma
======================
alpha
beta
gamma
[slitt@mydesk slitt]$

The braces bound tightly like this:
puts (my_array.collect {|word| word.capitalize})
Whereas do/end bind more loosely, like this:
puts (my_array.collect) do |word| word.capitalize} end
Note that the latter represents a syntax error anyway, and I've found no way to coerce do/end into doing the right thing simply by using parentheses. However, by assigning the iterator's results to a new array, that array can be used. It's one more variable and one more line of code. If the code is short, use braces. If it's long, the added overhead is so small a percentage that it's no big deal:
#!/usr/bin/ruby
my_array = ["alpha", "beta", "gamma"]
puts my_array.collect {
|word|
word.capitalize
}
puts "======================"
new_array = my_array.collect do
|word|
word.capitalize
end
puts new_array
[slitt@mydesk slitt]$ ./test.rb
Alpha
Beta
Gamma
======================
Alpha
Beta
Gamma
[slitt@mydesk slitt]$

Generally speaking, if you want to directly use the result of iterators, use braces. For longer blocks, do/end is more readable, and the overhead for the extra variable and line of code is trivial.

No comments:

Post a Comment