If you try to wrap your code in a method, it will not give you an error:
def some_method odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345] ints = odds_n_ends.select { |x| if x.is_a?(Integer) then return true end } puts ints end puts some_method
This code output is correct. But wait, where does the ints ??? Rubin did not guess. When you return inside Proc, you return to the scope of the entire method. In your example, you had no method in which you put your code, so after it encountered a “return”, it did not know where to “go”, where to continue.
Array # select basically works as follows: for each element of the array (represented by | x | in your code), it computes the block you just entered, and if the block evaluates to true, then this element will be included in the new array. Try removing the “return” from the second line and your code will work:
ints = odds_n_ends.select { |x| if x.is_a?(Integer) then true end }
However, this is not Ruby-ish itself; you do not need to specify Ruby to explicitly return true. Blocks (code between {}) are similar to methods, with the last expression being the return value of the method. Thus, this will work just as well:
ints = odds_n_ends.select { |x| if x.is_a?(Integer) }
Btw, there is a more elegant way to solve your problem:
odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345] ints = odds_n_ends.grep(Integer) puts ints
See this link . It basically says:
Returns an array of each element in the enumeration for which Pattern === element.
To understand the Pattern === element, just imagine that a pattern is a collection (say, a collection of integers). An element may or may not be an element of this set (integer). How to find out? Use ===. If you type in Ruby:
puts Integer === 34
it will be checked for true. If you put:
puts Integer === 'hey'
it will be false.
Hope this helps!