Make delicious recipes!

Introduction to Ruby



Ruby is a pretty popular language and frequently found among the top 20 languages in the TIOBE index. In the following tutorials, we will take a look at some of the most commonly-used ruby features. Some familiarity with programming is required (like knowledge of variables, if, for statements, classes and methods etc. in general programming languages) as those are too basic to be covered here.


# 1) Methods are declared with "def"
# 2) Args can have default values
# 3) Substitution in strings occurs by the use of #{variable-name}
# 4) Instance variables are declared using "@"

class Person
  def initialize(name = "Peter")
    @name = name
  end
  def print_name
    puts "Hi, my name is #{@name}!"
  end
  def go_for_a_walk
    puts "I, #{@name}, shall go for a walk."
  end
end


# 1) Objects are created using Class-name.new
# 2) Parentheses for a function call are optional

person = Person.new("Pat")
person.print_name
person.go_for_a_walk()




Person.instance_methods
# Shows all the methods for the given class


Person.instance_methods(false)
# Shows methods only for the given class and not its super-classes


# respond_to method tells if the given class has a particular
# string available for use as a method or not

Person.respond_to?("name")
=> false
Person.respond_to?("print_name")
=> true


# Use of attr_accessor to auto-generate getter/setter methods

class Person
  attr_accessor :name
end
Person.respond_to?("name")
=> true
Person.respond_to?("name=")
=> true

# attr_accessor creates getter and setter methods on the class
# So now, name can be read by using the method "name"
# and name can be set by using the method "name="







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal