Ruby/Development/gets

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

chomp takes off any Enters hanging out at the end of your string

puts "Hello there, and what\"s your name?"
name = gets.chomp
puts "Your name is " + name + "?  What a lovely name!"
puts "Pleased to meet you, " + name + ".  :)"



Get user"s input and process it, ignoring comments and exiting when the user enters the word "quit"

while line=gets.chomp do  # Loop, asking the user for input each time
  case line
  when /^\s*#/            
      next                
  when /^quit$/i          
    break                 
  else                    
    puts line.reverse     
  end
end



Parse command line

filename = nil
lines = 0               # Default means no truncating
loop do
  begin
    opt, arg = gets
    break if not opt
    case opt
      when "-h"
        puts "Usage: ..."
        break           # Stop processing if -h
      when "-f"
        filename = arg  # Save the file argument
      when "-l"
        if arg != ""
          lines = arg   # Save lines arg (if given)
        else
          lines = 100   # Default for truncating
        end
    end
  rescue => err
    puts err
    break
  end
end
puts "filename = #{filename}"
puts "lines    = #{lines}"



Read a line of input into $_

while gets             # Read a line of input into $_
  $F = split if $-a    # Split $_ into fields if -a was specified
  chop! if $-l         # Chop line ending off $_ if -l was specified
  # Program text here
end



Read your name from keyboard

puts "Please enter your name:"
name = gets
puts "Hello #{name}"



The Methods gets and chomp

puts "Hello there, and what\"s your name?"
name = gets
puts "Your name is " + name + "?  What a lovely name!"
puts "Pleased to meet you, " + name + ".  :)"



use gets method to read from standard input (text from your keyboard, by default).

#!/usr/bin/env ruby
print "Who do you want to say hello to? "
hello = gets
puts "Hello, " + hello



Use while loop to read a command

command = ""
while command != "bye"
  puts command
  command = gets.chomp
end
puts "Come again soon!"