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

    Join Date
    Jul 2008
    Location
    USA
    Posts
    42
    Rep Power
    6

    Array assignment problem


    Hi guys,

    Code:
    @theArray = []
    @theArray[0]= 155
    @theArray[1]= 55
    
    @theArray2 = []
    
    for i in (0..2)
     @theArray2[i] = @theArray[i].to_s(16)
    end
    doesnt work ?

    ArgumentError: wrong number of arguments (1 for 0)
    from (irb):75:in `to_s'
    from (irb):75
    from (irb):74:in `each'
    from (irb):74
    from ^C:0

    I want to be converting the elements of theArray to hex and copy them to the new theArray2. And do this in one step.

    Does anyone know how to fix this ?
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,534
    Rep Power
    1906
    you are using an array with 2 items, placed at index 0 and 1.

    in your loop you have (0..2) which will access item at index 0, 1 and 2, with index 2 no existing.

    what you want to use is (0...2) (with an extra dot, which means the vale 2 is not being used) or (0..1).
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2008
    Location
    USA
    Posts
    42
    Rep Power
    6
    thanks for the quick reply.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    To avoid such worries, ruby moves pretty heavily to the iterator philosophy. Arrays support iterators like each
    Code:
    irb(main):005:0> a = [1,4,2,7,6]
    => [1, 4, 2, 7, 6]
    irb(main):006:0> a.each { |x| puts x }
    1
    4
    2
    7
    6
    => [1, 4, 2, 7, 6]
    Now you dont need to worry about whether or not to add the extra '.' or not.
    Just food for thought.
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog

IMN logo majestic logo threadwatch logo seochat tools logo