Ruby part — 1

Ranjan Bajracharya
5 min readJan 10, 2018

--

Ruby is a powerful, flexible programming language you can use in web/Internet development, to process text, to create games, and as part of the popular Ruby on Rails web framework. . It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan. Ruby is:

  • High-level: Reading and writing Ruby is really easy — it looks a lot like regular English.
  • Object-oriented: It allows users to manipulate data structures called objects in order to build and execute programs.
  • Easy to use. Because everything in Ruby is an object , everything in Ruby has certain built-in abilities called methods.

for window you can download ruby interpreter from here

Beginning Of Ruby Programming

‘puts’ and ‘print’

The print command just takes whatever you give it and prints it to the screen. puts (for "put string") is slightly different: it adds a new (blank) line after the thing you want it to print. You use them like this:

puts "Hello World"
print "Hello World"

‘gets’

variable_name = gets.chomp

gets is the Ruby method that gets input from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line. (Your program will work fine without chomp, but you'll get extra blank lines everywhere.)

Comments

Single Line comets begins with# sign.

Multi-line comments begins with keyword =begin and end with =end, everything between those two expressions will be a comment

# This is single line comment=begin I’m a comment!
I don’t need any # symbols.
=end

Variables

Naming Conventions

By convention, these variables should start with a lowercase letter and words should be separated by underscores, like counter and masterful_method. Ruby won't stop you from starting your local variables with other symbols, such as capital letters, $s, or @s, but by convention these mean different things, so it's best to avoid confusion by doing what the Ruby community does.

Global Variables

Global variables begin with $. These variable are accessed from all place.

$global_variable = 10
class one
def var1
puts "Global variable is#{global_variable}"
end
end
class two
def var2
puts "Global variable is#{global_variable}"
end
end

#{variable} is called String Interpolation. It display the value assigned to that variable. In above program output of both put is 10.

Instance Variables

Instance variables begin with @. Each instance variable lives in memory for the life of the object it is owned by.

class Customer
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
end

Class Variables

Class variables begin with @@ and must be initialized before they can be used in method definitions.

class Customer
@@no_of_customers = 0
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end

Local Variables

Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block’s opening brace to its close brace {}.

Constants

Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.

class one
VAR1 = 100
def show
puts "Value of first Constant is #{VAR1}"
end
end

Data Types

Ruby has several data types. All data types are based on classes. The following are the data types recognized in Ruby:

  • Booleans
  • Symbols
  • Numbers
  • Strings
  • Arrays
  • Hashes

Boolean:

In Ruby the Boolean data type can have one of the two values: true or false. Boolean is a fundamental data type: one that is very common in computer programs.

Symbol

Ruby symbol is a sort of name. Symbols are used to represent other object. It’s important to remember that symbols aren’t strings. Symbols are generated by using an colon before an identifier, like :name. Several objects also have to_sym methods. These methods convert those objects to symbols.

The .object_id method gets the ID of an object—it's how Ruby knows whether two objects are the exact same object. Run the code in the editor to see that the two "strings" are actually different objects, whereas the :symbol is the same object listed twice.

puts “string”.object_id
puts “string”.object_id

puts :symbol.object_id
puts :symbol.object_id

Symbols pop up in a lot of places in Ruby, but they’re primarily used either as hash keys or for referencing method names.

symbol_hash = {
:one => 1,
:two = >2,
:three =>3,
}

Numbers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {…, -2, -1, 0, 1, 2, …} This set is infinite.

Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities like weight, height or speed

nil value Ruby has a special value nil. It is an absence of a value. The nil is a singleton object of a NilClass. There is only one nil; we cannot have more of it.

puts 4
puts 4.5
puts nil

A string is a data type representing textual data in computer programs. A Ruby string is a sequence of unicode characters. A string is an instance of the String. String literals are characters enclosed in double or single qoutes.

puts 'This is a simple Ruby string literal'

Array

Ruby arrays are ordered, integer-indexed collections of any object. Each element in the array has what’s called an index. The first element is at index 0, the next is at index 1, the following is at index 2, and so on. We can access elements of the array directly.

Creating Arrays

names = Array.new 
names = Array.new(20) #setting size of array

Some example with output

names = Array.new(4, "aaa",4.5)
puts "#{names}" #output:- 4, aaa, 4.5
puts names.length #output:- 3

Arrays of Arrays

Arrays of arrays are called multidimensional arrays, since the act of adding more arrays expands the array out of its string-like shape. For instance, the array in the editor is a two-dimensional array.

multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

multi_d_array.each { |x| puts “#{x}\n” }

Introduction to Hashes

A Hash is a collection of key-value pairs like this: “student” = > “section”. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

hash = { key1 => value1, key2 => value2, key3 => value3 }

countries= Hash.new
countries["Nepal"] = "Kathmandu"
countries["India"] = "New Delhi"
puts "#{countries['Nepal']}" #output:- Kathmandu

The hash syntax you’ve seen so far (with the =>symbol between keys and values) is sometimes nicknamed the hash rocket style.

This is because the => looks like a tiny rocket!

new_hash = { one: 1, two: 2, three: 3 }

new_hash = { one =>1, two => 2, three => 3 }

However, the hash syntax changed in Ruby 1.9.

new_hash = { one: 1, two: 2, three: 3 }

The two changes are:

  1. You put the colon at the end of the symbol, not at the beginning;
  2. You don’t need the hash rocket anymore.

--

--

Ranjan Bajracharya
Ranjan Bajracharya

Written by Ranjan Bajracharya

MSP 2017. Graduation in computer science and information technology. Studying MBA.

Responses (1)