Module: Nutella

Defined in:
lib/nutella/input.rb,
lib/nutella/version.rb

Constant Summary collapse

VERSION =

The current version of Nutella.

"0.13.1"

Class Method Summary collapse

Class Method Details

.input(prompt) ⇒ String

Takes input as described in Nutella#raw_input, but strips all leading and trailing whitespace.

Parameters:

  • prompt (String)

    the message to display to the user

Returns:

  • (String)

    the user’s input with excess whitespace stripped



26
27
28
# File 'lib/nutella/input.rb', line 26

def input(prompt)
  raw_input(prompt).strip
end

.int_input(prompt, err_msg = "Please enter a number.", repeat = true) ⇒ Integer

Takes an integer input from the user. If the user does not enter a valid integer value, display the error and ask them again, unless err_msg is nil, in which case it will not display any error message before asking again. If repeat is set to false, it will only ask once, exiting and returning nil if the first attempt fails.

Examples:

Ask the user to input their age

age = Nutella::int_input "Enter your age: "

Parameters:

  • prompt (String)

    the message to display to the user

  • err_msg (String, NilClass) (defaults to: "Please enter a number.")

    the error to show the user if they should enter an invalid input

  • repeat (Boolean) (defaults to: true)

    whether or not to continue prompting the user should their first input be unacceptable

Returns:

  • (Integer)

    the user’s numeric input as an integer



45
46
47
48
49
50
51
52
53
# File 'lib/nutella/input.rb', line 45

def int_input(prompt, err_msg = "Please enter a number.", repeat = true)
  str = ""
  until str[/^-?\d+$/]
    str = input prompt
    puts err_msg unless str[/^-?\d+$/] || err_msg.nil?
    return unless repeat
  end
  str.to_i
end

.raw_input(prompt) ⇒ String

Prints the given prompt to STDOUT, then reads text from STDIN until the user presses Enter.

Examples:

Comparison of taking input with and without Nutella

# Pure Ruby
print "Enter your name: "
name = STDIN.gets.chomp

# Ruby with Nutella
name = Nutella::raw_input "Enter your name: "

Parameters:

  • prompt (String)

    the message to display to the user

Returns:

  • (String)

    the user’s input



16
17
18
19
# File 'lib/nutella/input.rb', line 16

def raw_input(prompt)
  print prompt
  STDIN.gets.chomp
end