SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Jul 2008
    Location
    USA
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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
    l 0 l silver trophybronze trophy lo0ol's Avatar
    Join Date
    Aug 2002
    Location
    Palo Alto
    Posts
    5,329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There's a .hex method you can run on any string; perhaps that fits the bill for this?

  3. #3
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    (0..2) should be (0..1).

    A few hints:

    variable_name instead of variableName is idiomatic Ruby
    Don't use instance variables (with @ sign), but normal variables:

    Code ruby:
    the_array = []
    the_array[0]= 155
    the_array[1]= 55
     
    the_array = []
     
    for i in (0..1)
     the_array2[i] = the_array[i].to_s(16)
    end

    Ruby has array literals:

    Code ruby:
    the_array = [155,55]

    And Ruby has map:

    Code ruby:
    the_array = [155,55]
     
    the_array2 = the_array.map{|i| i.to_s(16)}

    (this does the same thing as your code)

    Can you see why Ruby is more productive? The code is much shorter an easier to read. And more importantly, with map there is no way to make the off-by-one error in your orignal code

  4. #4
    SitePoint Member
    Join Date
    Jul 2008
    Location
    USA
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thats nice. Thanks

  5. #5
    SitePoint Member
    Join Date
    Jul 2008
    Location
    UK
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, I'd forgotten ruby actually had a for function. Always use Array#map or Array#each myself.

  6. #6
    SitePoint Evangelist
    Join Date
    Feb 2006
    Location
    Worcs. UK
    Posts
    404
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    for x in y
      c = x
    end
    and
    Code:
    y.each |x| do
      c = x
    end
    are very similar. The main difference is that with the for loop c will be available outside the loop, whereas in the each example it will not be available outside the loop.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •