Why is "string".to_i = 0 but "9".to_i =9 - ruby

Hello I was wondering why this was the case and how to_i is defined.
simple question why does
"string".to_i
=> 0?
"9".to_i
=> 9

According to the documentation for to_i, "if there is not a valid a number at the start of str, 0 is returned".

Invoking .to_i on a string will return a number (in base 10) by interpreting valid numbers at the beginning of the string.
"string".to_i returns 0 because .to_i couldn't interpret a valid number from the start of the string. "9".to_i returns 9 because the leading (or in this case, the only) character is "9" and it could be interpreted as a valid number.
This doesn't mean that invoking .to_i on a string that starts with a letter will always return 0 though. For example, "b6".to_i(16) returns 182 because this means you want to interpret "b6" (in base 16, aka hexadecimal) as base 10.
See the documentation here: http://www.ruby-doc.org/core-2.1.0/String.html#method-i-to_i

Related

The code always outputs "not"

The following code always outputs "not":
print "input a number please. "
TestNumber = gets
if TestNumber % 2 == 0
print "The number is even"
else
print "The number is not even"
end
What is going wrong with my code?
The gets() method returns an object of type String.
When you call %() on a String object, the return value is a new String object (usually it changes the text. You can read more about string formatting here).
Since there are no String objects that == 0, the if/else will always take the same path.
If you want to use the return value of gets() like a number, you will need to transform it into one first. The simplest approach is probably to use the to_i() method on String objects, which returns a new 'Integer' object. If you're doing something where the user input will not always be an integer (e.g. 3.14 or 1.5), you might need to use a different approach.
One last thing: in your example the result of gets() is saved into a constant called TestNumber. Constants are different to normal variables, and they will probably cause problems if you're not using them intentionally. Normal variables don't start with capital letters. (You can read more about ruby variables here). In ruby you need to write you variable names like this: test_number.
I suspect your Testnumber variable might be interpreted as a string during the operation. make sure the testnum is converted to an integer first even if you put in say 100 it could be its being interpreted as the stirng "100" and not the integer 100.
A similar issue can be found here: Ruby Modulo Division
You have to convert TestNumber from string to integer, as your input has linefeed and/or other unwanted characters that do not match an integer.
Use TestNumber = gets.to_i to convert to integer before testing.

Keep leading zeroes when converting string to integer

For no particular reason, I am trying to add a #reverse method to the Integer class:
class Integer
def reverse
self.to_s.reverse.to_i
end
end
puts 1337.reverse # => 7331
puts 1000.reverse # => 1
This works fine except for numbers ending in a 0, as shown when 1000.reverse returns 1 rather than 0001. Is there any way to keep leading zeroes when converting a string into an integer?
Short answer: no, you cant.
2.1.5 :001 > 0001
=> 1
0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1.
Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case you are probably converting it into another kind of object (e.g a String).
If you want to keep the integer as Fixnum you will not be able to add leading zeros.
The real question is: why do you want/need leading zeros? You didn't provide such information in the question. There are probably better ways to achieve your result (such as wrapping the value into a decorator object if the goal is to properly format a result for display).
Does rjust work for you?
1000.to_s.reverse.to_i.to_s.rjust(1000.to_s.size,'0') #=> "0001"
self.to_s.to_i does convert the integer to a string and this string "0001" to an integer value. Since leading zeros are not required for regular numbers they are dropped. In other words: Keeping leading zeros does not make sense for calculations, so they are dropped. Just ask yourself how the integer 1 would look like if leading zeros would be preserved, since it represents a 32 bit number. If you need the leading zeros, there is no way around a string.
BUT 10 + "0001".to_i returns 11, so you probably need to override the + method of the String class.

how to check whether the string taken through gui is a binary string in matlab?

I am working on a watermarking project that embeds binary values (i.e 1s and 0s) in the image, for which I have to take the input from the user, and check certain conditions such as
1) no empty string
2) no other character or special character
3) no number other than 0 and 1
is entered.
The following code just checks the first condition. Is there any default function in Matlab to check whether entered string is binary
int_state = get(handles.edit1,'String'); %edit1 is the Tag of edit box
if isempty(int_state)`
fprintf('Error: Enter Text first\n');
else
%computation code
end
There is no such standard function, but the check can be easily implemented.
Use this error condition:
isempty(int_state) || any(~ismember(int_state, '01'))
It returns false (no error) if the string is non-empty and composed of '0's and '1's only.
The function ismember returns a boolean array that indicates for every character in int_state whether it is contained in the second argument, '01'. The advantage is that this can be generalized to arbitrary sets of allowed characters.
I think the 2nd and 3rd can be combined together as 1 condition: your input string can only be a combination of 0 and 1? If it is so, then a small trick with findstr can do that:
if length(findstr(input_str, '1')) + length(findstr(input_str, '0')) == length(input_str)
condition_satisfied;
end
tf = isnumeric(A) returns true if A is a numeric array and false otherwise.
A numeric array is any of the numeric types and any subclasses of those types.
isnumeric(A)
ans =
1 (when A is numeric).

Find a specific character in a string

I want to find a specific character in a given string of number for example if my input is:
1 4 5 7 9 12
Then for 4 the answer should be 1. My code is as follows:
secarr = second.split(" ")
answer = secarr.index(number) #here number is a variable which gets the character
puts answer
The above method works if I write "4" instead of number or any other specific character but does not work if I write a variable. Is there a method in ruby to do the same?
This is probably your variable number is an Integer, and secarr is an Array of Strings. Try to cast the number to string:
answer = secarr.index(number.to_s)

How to convert a number in a string to an integer

I have an output like "35%" from one command, and I stripped "%". Still, it's stored as a string. Is there a function to convert the string to integer?
You can simply do "35%".to_i which produces 35
For your exact problem:
puts 'true' if 35 == "35".to_i
output is:
true
Let's say your string is "35%". Start reading your string character by character. First your pointer is at '3'. Subtract '0'(ASCII 0) from this and multiply the result by 10. Go to the next character, '5' in this case and again subtract '0' but multiply the result by 1. Now add the 2 results and what you get is integer type 35. So what you are basically doing is subtracting '0' from each character and multiplying it by 10^(its position), until you hit your terminator(% here).

Resources