Is there any way to read the input by preserving its data type in ruby? If I use gets method, the value read will be a string.I cant convert the string input into the required type as the input type is not known in advance. please help
-
1If the input is text, it has a data type, and that type is String. Anything else will require conversion. – Nick Veys Oct 10 '13 at 05:10
-
In Ruby there is no concept of data type,rather all are objects.. BTW from string object in which object you want to convert? – Arup Rakshit Oct 10 '13 at 05:25
2 Answers
I cant convert the string input into the required type as the input type is not known in advance. please help
Ruby has the same issue - it has no way to tell what was intended by the user input, or what your program wants to do with it. The String
type is ideal for accepting character data from the keyboard, or a stream of bytes from a file. It is up to you to decide what to input, and how to interpret it.
Is there any way to read the input by preserving its data type in ruby?
There is no data type, other than String
that applies to generic keyboard input. However, all is not lost. You can use a variety of techniques to extract usable numbers, dates, IP addresses or whatever you need the input for.
If you know that an input value is supposed to be an integer, you can get a usable Ruby number from input simply like this:
number = gets.to_i
But if you are not so sure, or need to cover converting multiple possible types, you will need to test what types the string can be reasonably be converted from beforehand, and apply the conversion only afterward. For an example, see Test if string is a number in Ruby on Rails
There is no generic method for doing this, you will need to decide which conversions to test for and attempt depending on the nature of your application. There may be a gem or two out there which can reduce the pain of this if you really need to auto-convert to the most suitable Ruby type - but if such a thing exists, you would still need to test the class of the return value in order to decide what your application should or could do with the data (not much use getting a date/time when you wanted a floating point number).

- 1
- 1

- 26,512
- 6
- 76
- 94
A way to read/write objects in Ruby is to use serialization mechanism provided, by example, by YAML
Here is an example :
require 'yaml'
class A
attr_accessor :value, :text
def initialize
@value = 42
@text = "Hello World"
end
end
s = YAML::dump(A.new)
puts s
puts s.class
a = YAML::load s
puts a.class
puts a.value
You can see this output, where the correct class is found back after a dump
--- !ruby/object:A
value: 42
text: Hello World
String
A
42
Of course it is a useful way for non human input. You can do whatever you want with the string dump as writing it in a file or send it over the network.

- 2,849
- 16
- 23