Ruby Course – Worldwideasy – 03

Ruby Programming lesson 3. Today we going to learn more about it. Today I will focus on Getting User Input, Hashes, Method and If Statement. Finally, Create a simple Calculator. It can provide extensive knowledge.

Getting User Input in Ruby Programming

Uses any computer language user input is how Ruby does it. But it happens here in a very different way. We are focusing on that step by step.

First, you need to install Platformio-ide-terminal on Atom text editor.

  1. Go Settings
  2. >> install
  3. Search “Platformio-ide-terminal”
  4. Install it
  5. Search “Ruby Ide” and install it

The code below explains it to you.

puts "Enter Name "
name = gets
puts ("hello" + name)

Run using CMD this code output is hello with your entered name. see below another example

puts "Enter Your Name: "
name = gets.chomp()
puts "Enter Your Age: "
age = gets.chomp()
puts ("hello" + name + "you are " +age)

Hashes in Ruby Programming

A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values ​​given by a hash function are called hash values, hash codes, digests, or simply hashes. Values ​​are used to index a fixed-size table called a hash table.

Hashes are used to shorten a word or line of words and make it very easy to code. The following example illustrates this for you.

New York >> NY
Sri Lanka >> SL
Hello World >> HW 

As mentioned above, those words are short but the output is long.

Method

Object-oriented programming is a method of action related to a message and an object. An object consists of data and behaviors; These have an interface that specifies how the object can be used by its various customers.

You have an understanding of the method Now let us see how to use this for ruby

def sayhi
  puts "Hello user"
end

puts 'top'
sayhi
puts 'bottom'

see below code output

Output

Another example

def sayhi (name)
  puts ("Hi " + name)
end

sayhi ("harry")

This Code Output is Hi harry

Create Calculator Using Ruby

We create a very good Calculator based on the knowledge we have learned about ruby ​​so far. Here you also have to learn about if

puts "Enter First Number : "
num1 = gets.chomp().to_f
puts "Enter Opartor : "
op = gets.chomp()
puts "Second Number : "
num2 = gets.chomp().to_f

if op == '+'
  puts (num1 + num2)
else if op == "-"
  puts (num1 - num2)
else if op == "*"
  puts (num1 * num2)
else if op == "/"
  puts (num1 / num2)
else
  puts "invalid Enter"
end

Here you can input two numbers as output and select an operator and perform some action

Thank you for all!

More Ruby ClickHere!

See you Next Ruby Lesson Soon!