Featured

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.

 

Advertisements

How to create a child records with has_one associations

We knew about rails associations and one of the association is has_one. If we have has_one association. What will be parent and child records looks?

Small example: We have two models i.e. User and Profile

class User
    has_one :profile
end

class Profile
     belongs_to :user
end

So, If we create a record profile of respective user . What it exactly happens , Lets see through rails console: 

I am trying here to create a profile for user as normal which is having has_one association between user and profile models but in the below image you can see it throwing an error ” undefined method ‘new’ for nil:NilClass”. So , how can we create it ?

has_one relation example

We can create it as follows. It is different to create a compare to other association relations. We have to use  create_<model_name> method. In our example create_profile. Lets see the below screenshot how we can create a profile.

create_<model_name> method
you can find what all methods available in has_one association Methods in has_one

 

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