Taking fixnum as user input - ruby

I was wondering if there is a way to take user input as a fixnum. I can do something like a = gets.chomp.to_i, but is there anything similar in ruby to nextInt() in java, or do I need to do these conversions each time?

When you're working with input streams, like a file or the terminal, you're working with raw bytes. You never work directly with primitive types. If you want primitive types, you have to use methods to make sense of the bytes. In many cases, "working with raw bytes" is synonymous with working with strings, so strings types often have conversion methods to extract typed data out of them.
Java has the Scanner class, which does have a nextInt() method. It is used to extract a Java integer out of text. It does so by parsing the text and converting it to the requested primitive data type, in this case int. In order for it to work, you must give it an input source. When you wrap it around System.in, you get a Scanner that extracts data from standard input, which is usually connected to the terminal.
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
In Ruby, we can simply ask the string to try and convert itself to another type. If you want an integer:
line = gets # reads from standard input
i = line.to_i # converts the string to an integer
String's to_i method performs a very loose conversion, and returns zero if it couldn't figure out the number or if there was no number to begin with. It will never raise an exception and will always return a number, even if there was no number to parse.
The Integer() method performs a more strict conversion.

First of all, your gets.chomp.to_i works, but is not the right way. I don't know how you got that idea to attach chomp, but that has no meaning here. You should do gets.to_i. So, no, you don't need to do the conversion gets.chomp.to_i each time.
And the only thing Ruby can receive from a terminal input is a string. There is no way to receive anything other than a string from the terminal.

Related

Go Ints and Strings are immutable OR mutable?

What I am reading about ints and strings over internet is they are immutable in the nature.
But the following code shows that after changing the values of these types, still they points to the same address. This contradicts the idea behind the nature of types in python.
Can anyone please explain me this?
Thanks in advance.
package main
import (
"fmt"
)
func main() {
num := 2
fmt.Println(&num)
num = 3
fmt.Println(&num) // address value of the num does not change
str := "2"
fmt.Println(&str)
str = "34"
fmt.Println(&str) // address value of the str does not change
}```
A number is immutable by nature. 7 is 7, and it won't be 8 tomorrow. That doesn't mean that which number is stored in a variable cannot change. Variables are variable. They're mutable containers for values which may be mutable or immutable.
A Go string is immutable by language design; the string type doesn't support any mutating operators (like appending or replacing a character in the middle of the string). But, again, assignment can change which string a variable contains.
In Python (CPython at least), a number is implemented as a kind of object, with an address and fields like any other object. When you do tricks with id(), you're looking at the address of the object "behind" the variable, which may or may not change depending on what you do to it, and whether or not it was originally an interned small integer or something like that.
In Go, an integer is an integer. It's stored as an integer. The address of the variable is the address of the variable. The address of the variable might change if the garbage collector decides to move it (making the numeric value of the address more or less useless), but it doesn't reveal to you any tricks about the implementation of arithmetic operators, because there aren't any.
Strings are more complicated than integers; they are kind of object-ish internally, being a structure containing a pointer and a size. But taking the address of a string variable with &str doesn't tell you anything about that internal structure, and it doesn't tell you whether the Go compiler decided to use a de novo string value for an assignment, or to modify the old one in place (which it could, without breaking any rules, if it could prove that the old one would never be seen again by anything else). All it tells you is the address of str. If you wanted to find out whether that internal pointer changed you would have to use reflection... but there's hardly ever any practical reason to do so.
When you read about a string being immutable, it means you cannot modify it by index, ex:
x := "hello"
x[2] = 'r'
//will raise an error
As a comment says, when you modify the whole var(and not a part of it with an index), it's not related to being mutable or not, and you can do it

How does a loosely typed language know how to handle different data types?

I was working on a simple task yesterday, just needed to sum the values in a handful of dropdown menus to display in a textbox via Javascript. Unexpectedly, it was just building a string so instead of giving me the value 4 it gave me "1111". I understand what was happening; but I don't understand how.
With a loosely typed language like Javascript or PHP, how does the computer "know" what type to treat something as? If I just type everything as a var, how does it differentiate a string from an int from an object?
What the + operator will do in Javascript is determined at runtime, when both actual arguments (and their types) are known.
If the runtime sees that one of the arguments is a string, it will do string concatenation. Otherwise it will do numeric addition (if necessary coercing the arguments into numbers).
This logic is coded into the implementation of the + operator (or any other function like it). If you looked at it, you would see if typeof(a) === 'string' statements (or something very similar) in there.
If I just type everything as a var
Well, you don't type it at all. The variable has no type, but any actual value that ends up in that variable has a type, and code can inspect that.

Turn a human readable string into an image to be displayed with data-uris

Is there any conventional way to turn an arbitrary string into an image?
In my use case, lets say I want to have an image for each user that maps directly to that user's name.
The concept is similar to QR codes, except the output image is not designed to be readable, simple pretty and consistent.
ultimately i want something like:
def to_image(a_string)
... #magic
return a_data_uri
end
such that
# is always true
to_image("specific string") == to_image("specific string")
Ideally you'd end up with some nice looking fractal-art like image.
If what I'm describing is nonsensical, a function that can convert a string to a data-uri containing a qr code will do.
One possibility would be to hash the strings - this gives you unique numbers as output. Then you can pass these numbers as input param to a fractal generating function.
For hashing either use a real hash function, or (in case the number of users is limited) you can use a CRC function (CRC16, CRC32). Both approaches will give you uniques numbers as output. For CRC you must be a little bit more careful - for instance having 60K input strings and using CRC16 might end up with some clashes (different strings - same CRC16 number).

Calculating Event Horizons in Ruby

this is my first post here. I started using Ruby just 2 days ago and think it is an amazing language, however I have been getting stuck. My problem is I am wanting to calculate the event horizon of a black hole given an input defined in the code as "m" This will then be put into a calculation and the size then printed out to the screen. I did need it to be in binary and thats where I am having the issue.
Here is my code so far.
#Event Horizon Calculation Program
G = 6.67*10**-11
m = 20
C = 200000
R = G*m/(C**2)
puts "Here is the result in Binary."
R.to_i(2)
puts R
Now I do realise that the number are not accurate, that dosen't matter at the moment. I just need the function to work.
Thankyou,
Ross.
Your post is not even in a format of asking a question, but guessing from what you wrote, it seems that you are asking how to change your code so that it accepts an input to m and outputs the result. My answer is based on this assumption.
In order to take an input, use the 'gets' method. So, you may want to replace your 'm = 20' line with:
m = gets.to_f
'gets' accepts an input as a string, so you need to convert it to a numeric. to_f changes a string into a float. You can use to_i instead if you want an integer.
You have a line 'R.to_i(2)', and it seems like you want to output this, but you have two problems here. First of all, whatever that creates, it is only creating something in that position, and does not change the value of R, so, in effect, it actually does nothing. Second, ruby can accept numerals in source code written in different bases such decimal, binary, hex, etc., but it only has one internal representation, and you cannot output a numeral in binary. For your purpose, you need to convert it to a string that corresponds to a binary expression. For that, use the 'to_s' method. In fact, the 'to_i' method does not take an argument. Delete your line 'R.to_i(s)', and replace the line 'puts R' with:
puts R.to_s(2)

XPath: opposite of string() function?

In XPath it is possible to convert an object to string using the string() function. Now I want to convert the string back to an object.
I do understand it is not possible in some cases (for example for elements), because some information was lost. But it should be possible for simple types, like int or boolean.
I know, for numbers I can use number() function, but I want general mechanism which will work for any simple type variable.
Going to string is easy, because you've told it that you want a string.
Similarly, going to number is easy, because you've told it that you want a number.
But there is no generic way to say 'turn it back into x', because you haven't told it what x is.
(In other words, string() is like a cast like Java/C/C++/C# have. But there is no uncast.)
string() isn't an object serializer, so you can't deserialize.
Why do you want this? Perhaps there is another way of solving your problem.
If your object $x is the number 1234, then string($x) will be the string "1234".
If your object $x is a nodeset of 1000 XML elements, the first one being
<wibble><wobble>1<ping/>2</wobble>34</wibble>
then string($x) will be the string "1234".
The function is not a bijection, you can't have an inverse as many different values map to the same string.
In no language (that I know of) you can cast A to B and then call a magical function that reverts it back to whatever it was before you casted it.
The process of converting some data type into something else is always an unidirectional one - you lose the information what type it was before. That's because the new data type has no way of storing what it was before.
So, what are you trying to do? I strongly suspect that you ask this question because you are tackling a problem from the wrong end.

Resources