由於@ArupRakshit在他的評論中提及上面,gets
總是讓你一個String
。
你想要做的是獲取用戶的輸入並確定它是什麼。
例如,"1"
是String
,但是1
是Fixnum
。
[2] pry(main)> "1".class
=> String
[3] pry(main)> 1.class
=> Fixnum
在您的評論上面,你提到gets.to_i
給你一個整數。這有一個問題。 String#to_i
返回0對於不是數字的字符串:
[6] pry(main)> gets.to_i
hello
=> 0
[7] pry(main)> "hello".to_i
=> 0
所以基本上你得到一個String
,將確定其可能的類(ES)。
# add more Kernel methods here
POSSIBLE_CLASSES = [Integer, Float, Bignum, String]
str = gets.chomp # chomp gets rid of the \n that gets appended
# to your String because you press enter
# As @Stefan does it, but with meta-programming
POSSIBLE_CLASSES.collect { |p|
(Kernel.method(p.name).call(str); p) rescue nil
}.compact
最後一行的說明:
Kernel.Integer("1")
返回1
Kernel.Float("1.0")
回報1.0
所以基本上,我想調用內核的方法,它的名字是一樣的我的班。
Kernel.method(method_name)
將方法返回給我,然後使用字符串str調用該方法。
Kernel.Integer("hello")
會拋出ArgumentError
;將獲救,並將收回零。
所以基本上,上面的代碼將循環遍歷可能的類並嘗試用我們從控制檯獲取的字符串初始化它們。如果沒有例外,我們收集課程,否則爲零。然後我們壓縮數組(刪除nils),然後包含'有效'類。
請注意,我們的代碼僅支持Kernel
類型,並且可以輕鬆調整以支持其他類。
'#gets'總是給你的字符串... BTW –
這是真的。當我輸入gets.to_i時,它總是給出整數。那麼,什麼是方法來獲得輸入? –
這取決於你想要的有效類型... –