I've got a math function where I'm converting a base36 number to a
base 10 integer and it works wonderfully, except when the first
character is a zero.
I could get this method to work if I could look at the first position
in a string, and if it was a zero, I'd then add a zero to the first
position of the resulting string.
Here's the equation (and its compliment);
def calc_ovalue(barcode)
barcode.to_i(36)
end
def calc_other(barcode)
onum = calc_ovalue(barcode)
if onum.odd?
(onum + 1).to_s(36).upcase
else
(onum - 1).to_s(36).upcase
end
end
some examples of accepeting the first value and calculating the second
two are;
0N5F 0N5G ovalue = 30003
0V9B 0V9C ovalue = 40511
6JYV 6JYW ovalue = 305815
if you have a string @str, then
@str[0] will give you the charactercode of the first char
that's already enough to test against the charcode of a zero which is
48
if yo prefer to work with a string as result, use
@str[0,1]
this gives a string result (0 = from position, 1 = length)
or
@str[0..0]
returns a string too, the range is startposition to endposition
Matt,
I'm seeing how to test the first character of the incoming string
which is (barcode) (see function)
def calc_other(barcode)
onum = calc_ovalue(barcode)
if onum.odd?
(onum + 1).to_s(36).upcase
else
(onum - 1).to_s(36).upcase
end
if barcode[0] == 48
"0" + return
end
end
But then, I don't see how to attach the preceding zero if the incoming
(barcode) has one. I know this looks stupid, but what I'm attempting
is to add a zero to the first position of the result. I assume result
= string?
Thank you,
Kathleen
Marlon,
Yes. The problem is that if I submit a barcode like 0123 the other
barcode is calculated as 124. If there is a character other than zero
in the first position it works just fine.
Where are you suggesting that I put the return_val line of code you
show?
Is that gsub example putting a zero at the end of the string?
What / How would you amend the return value of the calc_other
function. Isn't the result of any method the value inside the 'return'
keyword?
If so, why can't the 'return' value be modified before the function
closes?
I seem to be having a problem 'seeing the forest through the trees'.
Kathleen