#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    2
    Rep Power
    0

    Basic question about ruby methods


    I'm new to Ruby and have a basic question I can't get my head around.

    If I have a simple loop like this:

    Code:
    array_thing = [1, 2, 3] 
    
     array_thing .each { |item| print item }
    But I want to add some logic to it such as (pseudo code below)

    Code:
    array_thing = [1, 2, 3] 
    
     array_thing .each { |item|   if item != number print "not a number" else print item }
    where do you typically put this when working with Ruby methods and the each method in particular?
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Hi,

    the block is exactly where to put the logic. And there isn't really an alternative, is it? Just like you put logic into the body of a for or while loop in other languages, you put it into a block in Ruby.

    Funny thing is, you've pretty much written down the actual code. All you gotta do is add a then and an end and replace the "item != numer" with an actual check like not item.is_a? Numeric.

    However, you shouldn't stuff everything into a single line, and you should rephrase the if statement and start with the positive case.

    Code:
    array_thing.each do |item|
      if item.is_a? Numeric
        print item
      else
        print "not a number"
      end
    end
    Note that you usually don't do explicit type checking in Ruby. Instead, you check if the object behaves in a certain way (i. e. has a specific method).
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    2
    Rep Power
    0
    Thanks for this. Appreciated.

IMN logo majestic logo threadwatch logo seochat tools logo