Implementation of Methods and Conditional statements in Ruby

0
1729

Today in this tutorial we will learn how to Write different methods and use of conditional statements in Ruby.

  • Follow the steps below and get the hands on experience :
  1. To start with ruby compiler go to
    Start->All Programs->RailsInstaller->Interactive Ruby
  2. 1
  3. After Opening the Interactive Ruby the following Command line interface will be displayed.
  4. 0

  5. To declare the method in ruby the syntax is as shown below :
  6. def methodname
    body of methods
    end
    

    1

    So in this if we have to create method the def keyword is used and to finish method end keyword is used.

  7. For Method With Arguments :
  8. Syntax is:

    def methodname(arg1,agr2,arg3…,argn)
    methodbody
    methodbody
    end
    

    The method with arguments can be displayed as in the following example:
    2

  9. System defined methods can also be declared as follows
  10. Example :
    The reverse function is as follows:

    'abcd'.reverse

    3

  11. If you want to know the list of all the methods in the ruby which may be working with string and numbers then use the following syntax :
  12.  “stringname”.methods 

    4

    number.methods

    5

  13. Now here is the exercise for Conditional Statements :
    1. if..else is one of the conditional statement
    2. Example :
      In this example we have taken variable fruit1 =”mango”

      fruit1 =”mango”

      we have taken one more variable fruit2 =”apple”

      fruit2 =”apple”

      Now if we compare it mango or apple it should display “This is a fruit” .

      if(fruit1=="mango")
      print 'This is fruit'
      end

      6

      As we can see in the above example we have taken variable
      fruit1 =”mango”
      so when we compare it with the following if statement it will display the following message :

      if(fruit1=="melon")
      print 'This is not mango'
      end

      7

    3. We can also put ‘&&’ and ‘||’ operator in it
    4. fruit1="Mango"
      fruit2="Grapes"
      if(fruit1=="Mango"&&fruit2=="Grapes")
      puts"I love both fruits"
      end

      8

  14. Thus we have learnt how to write methods and conditional statements in Ruby on Rails.

LEAVE A REPLY

Please enter your comment!
Please enter your name here