Read input from console in Ruby?

前端 未结 5 633
孤独总比滥情好
孤独总比滥情好 2020-12-23 02:50

I want to write a simple A+B program in ruby, but I have no idea how to work with the console.

5条回答
  •  自闭症患者
    2020-12-23 03:29

    If you want to make interactive console:

    #!/usr/bin/env ruby
    
    require "readline"
    addends = []
    while addend_string = Readline.readline("> ", true)
      addends << addend_string.to_i
      puts "#{addends.join(' + ')} = #{addends.sum}"
    end
    

    Usage (assuming you put above snippet into summator file in current directory):

    chmod +x summator
    ./summator
    > 1
    1 = 1
    > 2
    1 + 2 = 3
    

    Use Ctrl + D to exit

提交回复
热议问题