RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


A Java Developer's Guide to Ruby : Page 4

Ruby's versatility and flexibility complement Java well. That's why a Java developer who can program in Ruby is more effective and efficient than one who programs only in Java.

Ruby Code Blocks
Ruby uses code blocks as an additional way to iterate over data. These blocks offer more flexibility and power than the limited iteration functionality built into the Java language. The previous example showing basic string functionality used the stemmer gem to find the word stems of a string containing English words. The following example uses the String split method to tokenize a string using the space character as a word delimiter and then passes a code block defined using the { and } characters to mark the beginning and end of a code block (you also can use begin and end). Local variables in a block are listed between two | characters:
puts "longs trips study studying banking".split(' ')
puts "longs trips study studying banking".split(' ').each {|token| puts "#{token} : #{token.stem}"

This code snippet produces the following:


longs : long
trips : trip
study : studi
studying : studi
banking : bank

You can see another good use of code blocks in the following example, which uses the Array collect method. The collect method processes each array element and then passes it to a code block:

require 'pp'
pp ["the", "cat", "ran", "away"].collect {|x| x.upcase}
pp ["the", "cat", "ran", "away"].collect {|x| x.upcase}.join(' ')

In this example, the code block assumes that the elements are strings and calls the upcase method on each element. The collect method returns the collected results in a new array. It also uses the method join to combine all the resulting array elements into a string, separating the elements with the space character. This is the output:

["THE", "CAT", "RAN", "AWAY"]

Writing Methods That Use Code Blocks
You can use the yield method to call a code block passed to a method or function call. The following example uses the method block_given? to call yield conditionally if a code block is supplied. The method yield returns a value that is printed:

def cb_test name
	puts "Code block test: argument: #{name}"
	s = yield(name) if block_given?
	puts "After executing an optional code block, =#{s}"

This example calls function cb_test, first without a code block and then with one:

>> puts cb_test("Mark")
Code block test: argument: Mark
After executing an optional code block, =
=> nil
>> puts cb_test("Mark") {|x| x + x}
Code block test: argument: Mark
After executing an optional code block, =MarkMark
=> nil

The string value Mark is passed as an argument to yield, and inside the code block the local variable x is assigned the value Mark. The return value from the code block is MarkMark.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date