hac13
hac13

Reputation: 73

why does this ruby code not return anything?

I'm trying to take a number and return a string with dashes around any odd numbers. Also, the string should not begin or end with a dash.

I've written the following but it does not return anything:

def dasherize_number(num)
  string = num.to_s
  i = 0

  while i<string.length
    if (string[i].to_i % 2) != 0
      string[i] = '-' + string[i] + '-'
    end
    i += 1
  end

  if string[0] == '-'
    string.pop(1)
  end

  if (string.length - 1) == '-'
    string.pop(1)
  end

  string
end

It appears to be looping infinitely if I understand correctly; the console shows no output and doesn't allow me to do anything else unless I refresh. I've reviewed the code by each character, but I can't figure where it goes wrong.

Upvotes: 0

Views: 91

Answers (2)

Alfie
Alfie

Reputation: 2784

There were a lot of logical issues in your code. here's something that might just work for you

def dasherize_number(num)
  string = num.to_s
  str_len = string.length

  i = 0

  while i < str_len
    next if string[i] == '-'
    if (string[i].to_i % 2) != 0
      string[i] = '-' + string[i] + '-'
      str_len = string.length
      i += 3
    else
      i += 1
    end
  end

  if string[0] == '-'
    string = string[1..-1]
  end

  if (string[string.length - 1]) == '-'
    string = string[0..-2]
  end

  string.gsub('--', '-')
end

Explaination

  1. Firstly, you had this condition in your while loop i < string.length Which wouldn't work, because the length of the string keeps changing. So i've used a variable to store the value and update the variable if the string is updated.

  2. If the string is updated, we can be sure that we can skip the next two indexes. eg: number inputed -> 122 then after first iteration the string would be -1-22 so we don't want to run the same condition for the next index because, that would be 1 again, hence the infinite loop. (Hope you get the idea)

  3. pop wouldn't work on string, just because we can access characters using indexes like for arrays, we can't use pop for strings.

  4. To make sure there are no consecutive dashes, i've used gsub to replace them with single dash.

Upvotes: 1

Uzbekjon
Uzbekjon

Reputation: 11813

The problem seems to be in this part of the code:

while i<string.length
    if (string[i].to_i % 2) != 0
        string[i] = '-' + string[i] + '-'
    end
    i += 1
end

If your string contains odd number it increases its length by 2 more chars (2x-), but incrementing it by 1 (i+=1).

Assign initial string length to a var and check its length in the while loop.

string_length = string.length

while i < string_length
    if ((string[i].to_i % 2) != 0)
        string[i] = '-' + string[i] + '-'
    end
    i += 1
end

Upvotes: 0

Related Questions