3 Replies - 771 Views - Last Post: 10 December 2010 - 02:04 PM Rate Topic: -----

#1 huskerman007  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 26-December 09

Method Calling

Posted 10 December 2010 - 10:54 AM

def getter(yz)
    y = yz[0]
for i in 0..(yz.length-1)
        if yield(y, yz[i])
            y = yz[i]
        end
  end
return y
end


Given this method I have to call this method and in the code block I need to return the smallest item in the array. So I tried just getting the code block to just print out the array by doing this
getter([1,2,3]) { |y| print y}
. This gives me back 111. Its apparent that its not iterating through the array. How do I get it to iterate through the array so it prints out 123.

Is This A Good Question/Topic? 0
  • +

Replies To: Method Calling

#2 The Neoracle  Icon User is offline

  • Check, check, 1, 2.
  • member icon

Reputation: 21
  • View blog
  • Posts: 4,097
  • Joined: 30-March 01

Re: Method Calling

Posted 10 December 2010 - 11:09 AM

First, almost no idomatic ruby uses "for loop" syntax. Arrays are enumerable, so you should use something like each or map or collect to loop through it.

Is this psuedo code? It doesn't make any sense to me. Why would it every print out anyting other than 1? You're assigning 1 to y, and that's the only thing you're yielding to the block.

If you just want a string "123" returned why not do:

[1,2,3].sort.join


If you want hte smallest item in the array, why not do:
[2,3,1].sort.first

This post has been edited by The Neoracle: 10 December 2010 - 11:10 AM

Was This Post Helpful? 2
  • +
  • -

#3 MitkOK  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 32
  • View blog
  • Posts: 403
  • Joined: 09-August 07

Re: Method Calling

Posted 10 December 2010 - 01:52 PM

It's common mistake made by beginners to write C/Java/PHP in Ruby like the for loop.
And I guarantee you'll never see something closer to "for i in 0..(yz.length-1)" in Ruby code.
By the way The Neoracle is right, it doesn't clear what you're trying to do.
Was This Post Helpful? 0
  • +
  • -

#4 nimajneb  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 116
  • Joined: 04-August 10

Re: Method Calling

Posted 10 December 2010 - 02:04 PM

View PostMitkOK, on 10 December 2010 - 11:52 AM, said:

It's common mistake made by beginners to write C/Java/PHP in Ruby like the for loop.


I know I suffered from this. I've looked at some of my first ruby programs and it was ridiculous how bloated they were with Java-esque coding
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1