Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > block returns and hash element returns

Reply
Thread Tools

block returns and hash element returns

 
 
Trans
Guest
Posts: n/a
 
      11-06-2005
A question and a thought (or two).

Is there a way to return from a block without returning from the whole
method? Eg.

# This behavior
def double_collect( array )
array.collect { |v| v*2 }
end

# Nope, returns from double_collect
def double_collect( array )
array.collect { |v| return v*2 }
end

# Nope, returns only first iteration
def double_collect( array )
array.collect { |v| break v*2 }
end

Would something like #local_return be useful?

The reason I ask is b/c I was also thinking about a possbile special
form of 'return' that can handle hash assocations:

def double_collect( array )
array.collect { |v| local_return v => v*2 }
end
double_collect( [1,2,3] ) #=> { 1=>2, 2=>4, 3=>6 }

Presently I use a facet called #graph to do this:

array.graph { |v| [v, v*2] }

But returning that array just feels wrong (not to mention inefficient).

Thanks,
T.

 
Reply With Quote
 
 
 
 
gwtmp01@mac.com
Guest
Posts: n/a
 
      11-06-2005

On Nov 6, 2005, at 1:07 AM, Trans wrote:
> A question and a thought (or two).
>
> Is there a way to return from a block without returning from the whole
> method?


I think you are looking for 'next'

irb(main):001:0> [1,2,3,4].each { |x| next if x%2==0; puts "#{x} is
odd" }
1 is odd
3 is odd
=> [1, 2, 3, 4]



Gary Wright



 
Reply With Quote
 
 
 
 
Trans
Guest
Posts: n/a
 
      11-06-2005
#next, of course! Thank you.

Okay, so use #next in place of #local_return.

h1 = { :a => 1, :b => 2, :c => 3 }
h2 = h1.collect { |k,v| next k => v*2 }
h2 => { :a => 2, :b => 4, :c => 6 }

Could do this by modifying collect to merge hashes if they are the
yield result, but that's not exactly the same. since it would make it
impossible to collect hashes, and it would have not advantage over the
#graph method either --just substituting a hash for the array.

T.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
Where's the best version of Hash#pass and Hash#block? Phlip Ruby 9 03-09-2009 02:37 PM
Hash#select returns an array but Hash#reject returns a hash... Srijayanth Sridhar Ruby 19 07-02-2008 12:49 PM
Fo:Block can you check to see if a block contains any text by using the block id? morrell XML 1 10-10-2006 07:18 PM



Advertisments