如何检查变量是整数还是浮点数

时间:2018-09-02 11:54:27

标签: ruby

我想检查我的变量是整数还是浮点数。这是一个计算器。我不希望它无限循环。

我该怎么做?我尝试执行以下操作:

puts "Enter a number: "
num1 = gets.chomp()
while !(num1 == Integer.superclass or num1 == Float.superclass)
  puts "Enter an actual number: "
  num1 = gets.chomp()
end

3 个答案:

答案 0 :(得分:1)

通常,一种选择:

10.is_a? Integer # => true
10.5.is_a? Float # => true

或者,另一个:

String

但是由于输入是字符串,因此可以用猴子修补module StringFloatOrInteger def integer_or_float? begin !!Float(self) rescue false end end def integer_not_float? begin !!Integer(self) rescue false end end def integer? integer_not_float? & integer_or_float? end def float? !integer_not_float? & integer_or_float? end end String.include StringFloatOrInteger "home".integer? # => false "home".float? # => false "10".integer? # => true "10".float? # => false "10.5".integer? # => false "10.5".float? # => true 类的方法来检查字符串是整数还是浮点数:

def get_integer
  2.times do # or whatever times
    puts "Please enter an integer: "
    input = gets.chomp
    return input.to_i if input.integer?
  end
  return nil # or whatever
end

number = get_integer

在您的情况下,您可以这样使用,要求n次输入

{{1}}

答案 1 :(得分:1)

如果要检查某个变量是否为某种类型,可以只使用kind_of?:

<!DOCTYPE html>
<html>

<head>
  <title>Leaflet</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link type="text/css" rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
  <style>
    html,
    body,
    #leaflet {
      height: 90%
    }
  </style>
</head>

<body>
  <button id="hidem1">Hide1</button>
  <button id="showm1">Show1</button>
  <button id="hidem2">Hide2</button>
  <button id="showm2">Show2</button>
  <button id="hidem3">Hide3</button>
  <button id="showm3">Show3</button>    
  <div id="leaflet"></div>
  <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js"></script>

  <script>
    var map = L.map('leaflet', {
      layers: [
        L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
        })
      ],
      center: [48.85, 2.35],
      zoom: 12
    });

    // Example adapted from http://jsfiddle.net/b7LgG/3/
    // provided by @danzel https://github.com/Leaflet/Leaflet/issues/4#issuecomment-35025365
    // Images from Leaflet Custom Icons tutorial http://leafletjs.com/examples/custom-icons/
    //We don't use shadows as you can't currently specify what pane shadows end up in
    var greenIcon = L.icon({
      iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png',
      iconSize: [38, 95],
      iconAnchor: [22, 94],
      popupAnchor: [-3, -76]
    });
    var redIcon = L.icon({
      iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-red.png',
      iconSize: [38, 95],
      iconAnchor: [22, 94],
      popupAnchor: [-3, -76]
    });

    //Create panes for each of the sets of markers
    var pane1 = map.createPane('markers1');
    var pane2 = map.createPane('markers2');
    var pane3 = map.createPane('markers3');

    populate();

    function hide1() {
      pane1.style.display = 'none';
    }

    function show1() {
      pane1.style.display = '';
    }      

    function hide2() {
      pane2.style.display = 'none';
    }

    function show2() {
      pane2.style.display = '';
    }
      
    function hide3() {
      pane3.style.display = 'none';
    }

    function show3() {
      pane3.style.display = '';
    }

    L.DomUtil.get('hidem1').onclick = hide1;
    L.DomUtil.get('showm1').onclick = show1;
      
    L.DomUtil.get('hidem2').onclick = hide2;
    L.DomUtil.get('showm2').onclick = show2;
      
    L.DomUtil.get('hidem3').onclick = hide3;
    L.DomUtil.get('showm3').onclick = show3;      

    //Add 200 markers to each of the groups/layers
    function populate() {
      for (var i = 0; i < 200; i++) {
        new L.marker(getRandomLatLng(), {
          pane: pane1,
          color: 'green',
          //icon: greenIcon
        }).addTo(map);
        new L.circleMarker(getRandomLatLng(), {
          pane: pane2,
          color: 'red',
          //icon: redIcon
        }).addTo(map);
        new L.circleMarker(getRandomLatLng(), {
          pane: pane3,
          color: 'blue',
          //icon: redIcon
        }).addTo(map);
      }
      return false;
    }

    function getRandomLatLng() {
      return [
        48.8 + 0.1 * Math.random(),
        2.25 + 0.2 * Math.random()
      ];
    }
  </script>
</body>

</html>

答案 2 :(得分:0)

由于输入为字符串,因此您需要先将其转换为整数或浮点数

因此,如果您执行以下操作,并且输入为“ hello”,它将返回0.0

num1 = gets.chomp.to_f

如果您想严格验证它是否为整数,则可以通过

input = gets.chomp
until input.is_a?(Fixnum) do
 print "Please enter a number: "
 input = Integer(gets.chomp) rescue nil
end