Skip to content
Image

Factorial program in Ruby. ( A small and basic Interview question )

If you have an interview and if you comes under 3 years of experience or a fresher. You may face few basic interview question like Factorial, Fibonacci series, Amstrong etc.

Let’s see how we can write a factorial program in Ruby.

First of all What is a Factorial?

It is nothing but a product of an integer and all the integers below it.

For example

Factorial 5 (5!)   5 x 4 x 3 x 2 x 1 => 120

How we can achieve it in Ruby

We have so many ways to achieve this in Ruby. Let’s see the best one

def factorial(n)
if n <= 0
1
else
n * factorial(n-1)
end
end

Let’s see the output

1.9.2-p330 :008 > factorial(5)
=> 120

That’s it. We have so many other ways to achieve the factorial but the above one will give you the basic idea of the program in a recursive way.

 

Image

Difference between resource and resources in Rails routes

Source: Difference between resource and resources in Rails routes

Image

Difference between resource and resources in Rails routes

Have you ever observed the difference between resource and resources?
Do you know when to use resource instead of resources?Here I would like to explain based on my observations let’s take a
look.

As general we noticed that while using resource in the routes file the action we have are as follows

resource: new, create, edit, update, show, destroy

Here we found that the index action was missed. Yes While using resources we have index action but not in the resource.

Let’s see why?

the resource is a singular
resources is a plural

In some cases, we may have a resource that always lookup without an ID. Let’s assume we need to show current logged in User
details. So no need of ID as the current logged user is the key here.

Resources is used to handle any request on any record based on ID. While Resource will depend on the current record.

We also have a difference in defining a path in view pages to actions.

Hope this small explanation helps you

Simple Ruby code send mails

require ‘net/smtp’

message = <<MESSAGE_END
From: Your mail id <me@example.com>
To: There mail id <yout@example.com>
This is a test mail to check ruby code is working for sending mails ?

MESSAGE_END

Net::SMTP.start(‘localhost’) do |smtp|
smtp.send_message message, ’email1@example.com’,
’email2@example.com’
puts “mail sent”
end

Fetch ipaddress and get location using ruby

require ‘rubygems’
require ‘geocoder’
require ‘socket’
    def local_ip
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect ‘64.233.187.99’, 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

ip_add =  local_ip

puts “your ip :” +ip_add
location = Geocoder.search(“#{ip_add}”)

location.each do |lc|
puts lc.city
if lc.city == “”
puts “this ip is reserved not able to fetch details “
end
end

Get IPaddress using ruby

Install socket gem and require it in you code

require ‘socket’

// local_ip is custom method to fetch ip address of the system u connected to global through //internet
    def local_ip
     orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off    reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect ‘64.233.187.99’, 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

ip_add =  local_ip

puts “your ip :” +ip_add

Mongoid in Ruby on Rails

Mongoid  is an Object-Document-Mapper (ODM) for MongoDB written in Ruby which works similar to ORM to other database in rails application.
Ruby developers who have been using Active Record or Data Mapper, while leveraging the power of MongoDB’s schemaless,performant document-based design, dynamic queries.

class Project
include Mongoid::Document
field :name, type: String
embeds_many :developers
end

class Developer
include Mongoid::Document
field :name, type: String
embedded_in :project
end

While using mondoDB in Rails application we need to include mongoid:Document in every model in our applications.

filed is the field name and the datatype we are specifying

embeds_many is nothing but has_many relationship In this way we can use mongoid in our rails application this is the simple exaplination about mongoid usage.

Country name using ip address

We can get the country name base on ip address

Using ‘ip2country’ gem we can do this but this gem can be possible to use in ruby 1.8.7 only(not sure )

require ‘rubygems’
require ‘ip2country’

ip2c = IP2Country.new
ip   = ‘88.22.52.35’

if country = ip2c.lookup(ip)
puts “#{ip} belongs is located in: #{country.name} (#{country.cc})”
else
puts “The region for #{ip} could not be determined.”
end

More repeated characters in a string

puts “Enter a string”
string = gets
puts string.scan(/((.)\2*)/).group_by{|s, c| s.length}.max.last.map{|s, c| c}

MongoDB introduction

MongoDB is an open source document-oriented database management system which comes under NoSQL family databases.Mongodb stores the data in JSON format instead of storing as a traditional database style in tables which relational database do.And also contains dynamic schema which helps to integrate it in applications and makes that application runs faster.

Any field in a MongoDB document can be indexed is the key feature .

Install MongoDB in Ubuntu.
Run the following command to import the 10gen public GPG Key in your terminal

sudo apt-key adv –keyserver keyserver.ubuntu.com –recv 7F0CEB10

Create a /etc/apt/sources.list.d/10gen.list file using the following command.

echo ‘deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen’ | sudo tee /etc/apt/sources.list.d/10gen.list

Update

sudo apt-get update

Install Packages

sudo apt-get install mongodb-10gen

you have successfully installed MongoDB!

Now you can start MongoDb as a service by the following command

sudo service mongodb start

To stop the service

sudo service mongodb stop

To restart the service

sudo service mongodb restart

After starting the service you can use mongodb client using mongo command

Run “mongo” command in the terminal

Now here is the important commands to use mongodb

To see all the databases

show dbs

To use the database

use database_name

To list out all the collections nothing but tables in general words

show collections

To insert data

Example syntax

db.table_name.insert({column_name:’value’,primary:true})

To find the record(s)

db.table_name.find()

also you can do

var result = db.table_name.find()

result.next()

result

For example you have normal query like

select * from emp where name=”ram”;

is looks like

db.emp.find({id:’ram’})

select * from emp where salary > 10000;

is looks like

db.emp.find({salary: {$gt: 10000}})

Note : to use greater than or equal to use ‘$gte’ and similarly less than or equal to ‘$lte’ .

It is also having maximum 4mb of document size.

%d bloggers like this: