DEV Community

Cover image for Creating Python's Input Function In Ruby
Lucretius Biah
Lucretius Biah

Posted on • Edited on • Originally published at kudadam.com

Creating Python's Input Function In Ruby

Repost from my blog

Ruby is a general-purpose programming language and it's syntax is close to Python's own.
When I started learning Ruby, I was marveled at it's simplicity.
Since I was coming from a Python background. I found it very easy to learn. Because of it's similarity in syntax, I wanted some of Python's function in Ruby.
One of the functions I wanted to implement was the input() function. The reason was that, Ruby unlike Python, you will need to use both puts and gets if you want to get a user's input whiles displaying text in Ruby.

Creating our function

Well, to create this function in Ruby is very simple. Just open your Ruby file and type the following code inside

def input(prompt ='')
    puts prompt
    return gets
end
Enter fullscreen mode Exit fullscreen mode

Explaining the function

Well, so as we can see, the function is just four lines of code. Pretty simple huh!
The function was made to just replicate Python's own so they work in the same way.
The input function takes an optional parameter called prompt. On the next line, the puts method displays the prompt to stdout and then the gets method retrieves any user input and returns it.

Trying out the function

In order to use the method we just created, make sure the code is in the same file as the one you are working with.

name = input("What is your name?")
print "Hello " + name
Enter fullscreen mode Exit fullscreen mode

In our example, we called our function with the string "What is your name?" and the value was stored in the variable name. On the next line, we printed 'Hello' + name.

See, that wasn't hard! 😄

Top comments (1)

Collapse
 
nikstojkov profile image
nikstojkov

Currently learning a bit of ruby through CodeAcademy, and this makes me so happy! I'm a total beginner, but same as you, my self taught 'background' (albeit thin) is python.