What is Readline?

Grace Yuiko Nakano
2 min readJul 26, 2021

HackerRank Challenge Day 1

I just completed my first HackerRank challenge. I figured that the first day would not be too challenging with the level marked easy but boy, was I wrong. Thank goodness for Readline module.

Complete the code in the editor below. The variables i, d, and s are already declared and initialized for you. Input:i = 4
d = 4.0
s = 'HackerRank'
Output:
8
8.0
HackerRank is the best place to practice code!
You must:1. Declare variables: one of type int, one of type double, and one of type String.2. Read lines of input from stdin (according to the sequence given in the Input Format section below) and initialize your variables.Use the operator to perform the following operations:A. Print the sum of plus your int variable on a new line.B. Print the sum of plus your double variable to a scale of one decimal place on a new line.C. Concatenate with the string you read as input and print the result on a new line.

I thought to myself, ok this seems straight forward:

puts (i * 2).to_i
puts (d * 2).to_f
puts s + ' is the best place to practice code!'

I ran the code:

Input:
i = 12
d = 4.0
s = 'HackerRank'
Your output:
8
8.0
HackerRank is the best place to practice code
Expected Output:
16
8.0
HackerRank is the best place to practice code!

Okay, my output was based on the variables that have already been declared and initialized. How could I access the next inputs for each of these variables?

Readline is a module that has built in methods that allow you to read through the stream of inputs line to line. This makes it easier to access the input and read the user output.

Ruby:i = 4
d = 4.0
s = 'HackerRank'
i2 = readline.to_i
d2 = readline.to_f
s2 = readline.to_s
puts (i + i2).to_i
puts (i + d2).to_f
puts (s + s2).to_s

It allows us to access the next input line and print sum of the value and the user output.

JavaScript:i = 4
d = 4.0
s = 'HackerRank'
let i2 = parseInt(readLine()) // we are in JS, must be camelcase
let d2 = parseFloat(readLine())
let s2 = readLine()
console.log(i + i2)
console.log(d + d2).toFixed(1))

// toFixed is fix point notation indicating the number of decimal places after the integer
console.log(s +s2)

Readline module is especially useful tool to use when dealing with CLI prompts. I will always remember to keep this in mind.

--

--

Grace Yuiko Nakano

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict