What is the output of the following programs

Note : Please find the answers manually

——————————————————–

1. Question 1

@a=[34,45,56,2,13,54]

@a.sort!

@a.reverse

puts @a[4] gives,

a) 13 b)54 c) 45 d) 56

——————————————————–

2. Question 2

@a=[34,45,56,2,13,54]

@a=@a.length.to_a.join

puts @a.class gives,

a) fixNum b)Array c) String d) ERROR ——————————————————–

3. Question 3

@a=[34,45,56,2,13,54]

@a=@a[5,4]

puts @a gives,

a) 13 b)54 c) 45 d) 56

——————————————————–

4. Question 4

@a=[34,45,56,2,13,54]

@a= @a.flatten

puts @a gives,

a) The reverse order b) NIL c) NULL d) Same Order

——————————————————–

5. Question 5

@a=[34,45,56,2,13,54]

@b= @a.min + @a.max + @a.first + @a.last

puts @b gives,

a) 92 b) 144 c) 146 d) 112

——————————————————–

6. Question 6

@a=[34,45,56,2,13,54]

@b= @a[2].value+@a[3].value

puts @b gives,

a) Argument Error b) 58 c) NomethodError d) 0

——————————————————–

7. Question 7

@a=[34,45,56,2,13,54]

@b= @a[2].display.to_i + @a[3].display.to_i

puts @b gives,

a) Error b) 58 c) 5620 d) 562

——————————————————–

8. Question 8

@a=[34,45,56,2,13,54]

@b= @a.rindex(13) + @a.values_at(4)[0]

puts @b gives,

a) Error b) 17 c) 47 d) 7

——————————————————–

9. Question 9

@a=[34,45,56,2,13,54]

@a.insert(6)

@a.insert(6,7)

@a << [137,89]

@b=@a.length

puts @b gives,

a) Error b) 10 c) 9 d) 8

——————————————————–

10. Question 10

@a=[34,45,56,2,13,54]

@b= @a.__id__.class

puts @b gives,

a) Error b) Array c) Nil class d) FixNum

Send your answers as a Comments of this article upto Oct 31 Result Date: Nov 1 (List of the names who scored 100%)

Modal Dialog + Ruby — Sample program

Installation

1. ruby 1.8.6

2. comamnd prompt

C:> gem install wxruby

Code:

require ‘wx’
include Wx

class MyFrame < Frame
def initialize()
super(nil, -1, ‘Jazzez’)
# First create the controls
@my_panel = Panel.new(self)
@my_label = StaticText.new(@my_panel, -1, ‘URL’, DEFAULT_POSITION, DEFAULT_SIZE, ALIGN_CENTER)
@my_textbox = TextCtrl.new(@my_panel, -1, ‘Default Textbox Value’)
#@my_combo = ComboBox.new(@my_panel, -1, ‘Default Combo Text’, DEFAULT_POSITION, DEFAULT_SIZE, ['Item 1', 'Item 2', 'Item 3'])
@my_button = Button.new(@my_panel, -1, ‘My Button Text’)
# Bind controls to functions
evt_button(@my_button.get_id()) { |event| my_button_click(event)}
# Now do the layout
@my_panel_sizer = BoxSizer.new(VERTICAL)
@my_panel.set_sizer(@my_panel_sizer)
@my_panel_sizer.add(@my_label, 0, GROW|ALL, 2)
@my_panel_sizer.add(@my_textbox, 0, GROW|ALL, 2)
#@my_panel_sizer.add(@my_combo, 0, GROW|ALL, 2)
@my_panel_sizer.add(@my_button, 0, GROW|ALL, 2)
show()
end

def my_button_click(event)
a= @my_textbox.get_value
b=a.to_i+1
@new= StaticText.new(@my_panel, -1, “#{b}”, DEFAULT_POSITION, DEFAULT_SIZE, ALIGN_CENTER)
@my_panel_sizer.add(@new, 0, GROW|ALL, 2)
end

end

class MyApp < App
def on_init
MyFrame.new
end
end

MyApp.new.main_loop()

Comments are always welcome

Print 1 to 10000
Why this program need ?:

1.Run a program to print 1 to 100000

2. programs interrupted when printing 497

3. Now run once again, It starts with again 1 to … .. Right ?

4. So This is the program to avoid that issue. Enjoy the program


Code:

i=0
file=File.open(“count.html”,”a”)
x= file.stat.size
if  x == 0 then
while i < 1000000
puts i
file.puts i
i+=1
end
else
s=File.readlines(“count.html”)
#s.each do |sing|
#x=sing
#end
x= s.last
i=x.to_i
i+=1
while i < 1000000
puts i
file.puts i
i+=1
end
end

Thanks,

P.Raveendran

Link Scraping from any URL

December 5, 2008

Link Scraping from any URL:

1. Need to install Ruby1.8.6

2. Need to install gems –> gem install mechanize (How to install gems ?)

Ruby Code:

require ‘rubygems’
require ‘mechanize’
agent = WWW::Mechanize.new
url = “http://google.com”

@overall=[]

@first=[]
@second=[]

page = agent.get(url)
page.links.each do |one|
href=one.uri
#puts href.class
if href.class == URI::Generic
#puts href.to_s[0,1] ==
@first << href=url+href.to_s if “#{href.to_s[0,1]}” == “/”
else #href.class == URI::HTTP
@first << href
end
end
@first.uniq!
puts @first

Comments are always welcome

regards,

P.Raveendran

If using the import interface, you can do it like this:

$terminal = HighLine.new($stdin, $stderr)

ask( � )

Otherwise, you can just build the proper HighLine instance and use it:

hl = HighLine.new($stdin, $stderr)

hl.ask( � )

Regards,

P.Raveendran

Hi All,

These are all some programs solution of Ruby forum asked questions by Users. i replied them and also want to share here…

Code 1 :

def run
arr=["Raveendran","jazzezravi","jazzez","ravi","jazzezravendran"]
ram(arr)
end
def ram(arr)
arra=arr
like = [" good boy", " bad boy"," nice boy"," Gentle man"]
puts arra[rand(5)] + like[rand(4)]
end

def raja(arr)
j=0
arr=["Arun","Babu","Chitra","David","Einstein"]
while j<4 do
puts arr[j]
j+=1
end
end
5.times { run; sleep(2)}

Output:

ravi good boy
ravi good boy
jazzezravi bad boy
ravi Gentle man
jazzezravi Gentle man

————————————————————————–

Code 2:

class Bird
def preen
puts “I am cleaning my feathers.”
end
def fly
puts “I am flying.”
end
end

class Penguin<Bird
def fly
fail “Sorry. I’d rather swim.”
end
end

p=Penguin.new
puts p.preen
puts p.fly

Output:

inher2method.rb:12:in `fly’: Sorry. I’d rather swim. (RuntimeError)
from inher2method.rb:18
I am cleaning my feathers.
nil

————————————————————————

Code 3:

# ansi_colors.rb
#
# Created by James Edward Gray II on 2005-05-03.
# Copyright 2005 Gray Productions. All rights reserved.

require “rubygems”
require “highline/import”

# Supported color sequences.
colors = %w{black red green yellow blue magenta cyan white}

# Using color() with symbols.
colors.each_with_index do |c, i|
say(“This should be <%= color(‘#{c}’, :#{c}) %>!”)
if i == 0
say( “This should be ” +
“<%= color(‘white on #{c}’, :white, :o n_#{c}) %>!”)
else
say( “This should be ” +
“<%= color( ‘#{colors[i - 1]} on #{c}’,
:#{colors[i - 1]}, :o n_#{c} ) %>!”)
end
end

# Using color with constants.
say(“This should be <%= color(‘bold’, BOLD) %>!”)
say(“This should be <%= color(‘underlined’, UNDERLINE) %>!”)

# Using constants only.
say(“This might even <%= BLINK %>blink<%= CLEAR %>!”)

# It even works with list wrapping.
erb_digits = %w{Zero One Two Three Four} +
["<%= color('Five', :blue) %%>"] +
%w{Six Seven Eight Nine}
say(“<%= list(#{erb_digits.inspect}, :columns_down, 3) %>”)

Output:

This should be black!
This should be white on black!
This should be red!
This should be black on red!
This should be green!
This should be red on green!
This should be yellow!
This should be green on yellow!
This should be blue!
This should be yellow on blue!
This should be magenta!
This should be blue on magenta!
This should be cyan!
This should be magenta on cyan!
This should be white!
This should be cyan on white!
This should be bold!
This should be underlined!
This might even blink!
Zero Four Eight
One Five Nine
Two Six
Three Seven

------------------------------------------------------------------------

Code 4:

require 'win32ole'
fso = WIN32OLE.new('Scripting.FileSystemObject')
folder = fso.GetFolder('C:\Documents and Settings\raveendran\My Documents\My Pictures\Trubee')
puts folder.name
puts folder.size
puts folder.path

Output:

Trubee
14948754
C:\Documents and Settings\raveendran\My Documents\My Pictures\Trubee

-----------------------------------------------------------------------------

High line Example Code 5:

require "highline/import"

zipcode = ask("Zip? ") { |zip| zip.validate = /\A\d{5}(?:-?\d{4})?\Z/ }

Output:

Zip? hiuhi8
Your answer isn't valid (must match /\A\d{5}(?:-?\d{4})?\Z/).
? ttrtrt
Your answer isn't valid (must match /\A\d{5}(?:-?\d{4})?\Z/).
? 90204

---------------------------------------------------------------------------

HighLine Example Code 6:

#!/usr/local/bin/ruby -w

require "rubygems"
require "highline/import"

# The old way, using ask() and say()...
choices = %w{ruby python perl}
say("This is the old way using ask() and say()...")
say("Please choose your favorite programming language:")
say(choices.map { |c| " #{c}\n" }.join)

case ask("? ", choices)
when "ruby"
say("Good choice!")
else
say("Not from around here, are you?")
end

# The new and improved choose()...
say("\nThis is the new mode (default)...")
choose do |menu|
menu.prompt = "Please choose your favorite programming language? "

menu.choice :ruby do say("Good choice!") end
menu.choices(:python, :perl) do say("Not from around here, are you?") end
end

say("\nThis is letter indexing...")
choose do |menu|
menu.index = :letter
menu.index_suffix = ") "

menu.prompt = "Please choose your favorite programming language? "

menu.choice :ruby do say("Good choice!") end
menu.choices(:python, :perl) do say("Not from around here, are you?") end
end

say("\nThis is with a different layout...")
choose do |menu|
menu.layout = :o ne_line

menu.header = "Languages"
menu.prompt = "Favorite? "

menu.choice :ruby do say("Good choice!") end
menu.choices(:python, :perl) do say("Not from around here, are you?") end
end

say("\nYou can even build shells...")
loop do
choose do |menu|
menu.layout = :menu_only

menu.shell = true

menu.choice(:load, "Load a file.") do |command, details|
say("Loading file with options: #{details}...")
end
menu.choice(:save, "Save a file.") do |command, details|
say("Saving file with options: #{details}...")
end
menu.choice(:quit, "Exit program.") { exit }
end
end

Output:

This is the old way using ask() and say()...
Please choose your favorite programming language:
ruby
python
perl
? ruby
You must choose one of ["ruby", "python", "perl"].
? runy
You must choose one of ["ruby", "python", "perl"].
? 1
You must choose one of ["ruby", "python", "perl"].
? perl
Not from around here, are you?

This is the new mode (default)…
1. ruby
2. python
3. perl
Please choose your favorite programming language? 1
Good choice!

This is letter indexing…
a) ruby
b) python
c) perl
Please choose your favorite programming language? ruby
You must choose one of ["a", "b", "c", :ruby, :python, :perl].
? a
Good choice!

This is with a different layout…
Languages: Favorite? (ruby, python or perl) ruby
Good choice!

You can even build shells…
load, save, quit or help? q

—————————————————————————

Transpose Code 7:

arr = ["abc", ["def1", "def2", "def3"]]
arr_final=[]
arr[0] = [arr[0]] * arr[1].size
p arr.transpose

Output:

[["abc", "def1"], ["abc", "def2"], ["abc", "def3"]]

———————————————————————–

Astrlrologicel help Code 8:

class Reservoir
def main

puts “Please Enter the name”
b=gets()

a=b.downcase
puts a
val={“a”=>1,”j”=>1,”s”=>1,
“b”=>2,”k”=>2,”t”=>2,
“c”=>3,”l”=>3,”u”=>3,
“d”=>4,”m”=>4,”v”=>4,
“e”=>5,”n”=>5,”w”=>5,
“f”=>6,”o”=>6,”x”=>6,
“g”=>7,”p”=>7,”y”=>7,
“h”=>8,”q”=>8,”z”=>8,
“i”=>9,”r”=>9}

num=[]
i=0
#puts a
while i < a.length do
num << val[a[i,1]]
i+=1
end
mind(num)
end

def mind(num)
no=[]
no=num
j=0

final=0
while j < no.length
final +=num[j].to_i
j+=1
end
output= final.to_s
if output.length !=1
output2=output.split(//)
mind(output2)
else
puts final
end
end
end

res=Reservoir.new
res.main

Output:

Please Enter the name
raveendran
3 # This number will give some astrological theories.

————————————————————————

MYSQL Code 9:

require ‘mysql’

my_array= ["google.com","yahoo.com"]

db = Mysql::new(“localhost”, “root”, “”, “new_development”)

my_array.each do |a|
puts a
b = a.collect{|x| x = “‘” + x + “‘”}
puts b
c = b.join(“,”)
puts c
sql = “INSERT INTO sites VALUES (3,#{c},0,0);”
db.query(sql)
end

——————————————————————

Big Decimal Code 10:

require ‘bigdecimal’
x = BigDecimal(“123.6″) – BigDecimal(“123″)

puts x.to_f

puts f=123.6 – 123

Output:

0.6
0.599999999999994

——————————————————————-

File Stat Code 11:

puts a= File.stat(“hi.txt”).uid
puts a= File.stat(“hi.txt”).nlink

Output:

0

1

——————————————————————

HTML Tag Helper Code 12:

source=File.open(“wordpress.txt”)

search=["<html","</html>","<head","</head>","<body","</body>","<table","</table>","<tr","</tr>","<td","</td>",
"<th","</th>","<p","</p>","<div","</div>","<span","</span>",
"<script","</script>","<ul","</ul>","<li","</li>","<ol","</ol>","<a","</a>","<h1","</h1>","<h2","</h2>",
"<h3","</h3>","<h4","</h4>","<h5","</h5>","<h6","</h6>","<font","</font>"]

tag=[]
source.each do |line|
i=0

while i < search.length do
taghelp = line.downcase.match(search[i]).to_s
tag << taghelp unless taghelp.empty?
i+=1
end

end

j=0
while j< search.length do

count= tag.grep(search[j])
puts count.length.to_s + search[j].to_s + ” tag”
j+=1

end

WordPress.txt File has –> View source code of the testing web page

Output:

1<html tag
1</html> tag
1<head tag
1</head> tag
1<body tag
1</body> tag
0<table tag
0</table> tag
0<tr tag
0</tr> tag
0<td tag
0</td> tag
0<th tag
0</th> tag
0<p tag
0</p> tag
117<div tag
117</div> tag
30<span tag
30</span> tag
14<script tag
14</script> tag
0<ul tag
0</ul> tag
2<li tag
0</li> tag
0<ol tag
0</ol> tag
17<a tag
17</a> tag
12<h1 tag
12</h1> tag
0<h2 tag
0</h2> tag
0<h3 tag
0</h3> tag
0<h4 tag
0</h4> tag
0<h5 tag
0</h5> tag
0<h6 tag
0</h6> tag
0<font tag
0</font> tag

—————————————————————-

Infinite Loop Code 13:

class X
def m; “m”; end
end

class Y < X
def self.method_added(sym)
puts sym
#return if /^__/ === sym.to_s
alias_method(“__#{sym}”, sym)
remove_method(sym)
end
def m; m; end
end

#class Y
#def m; m; end
#end

Y.new

Output:

m
__m
____m
______m
________m
__________m
____________m
______________m
________________m
__________________m

—————————————————————————

Next 30 days List Code 14:

date= Date.today
enddate=date + 30
weekday=[0,1,2,3,4,5,6]

while enddate > date
puts date.to_s+” sunday” if date.wday==0
puts date.to_s+” monday” if date.wday==1
puts date.to_s+” tuesday” if date.wday==2
puts date.to_s+” Wednesday” if date.wday==3
puts date.to_s+” thursday” if date.wday==4
puts date.to_s+” friday” if date.wday==5
puts date.to_s+” saturday” if date.wday==6
date+=1
end

Output:

2008-08-08 friday
2008-08-09 saturday
2008-08-10 sunday
2008-08-11 monday
2008-08-12 tuesday
2008-08-13 Wednesday
2008-08-14 thursday
2008-08-15 friday
2008-08-16 saturday
2008-08-17 sunday
2008-08-18 monday
2008-08-19 tuesday
2008-08-20 Wednesday
2008-08-21 thursday
2008-08-22 friday
2008-08-23 saturday
2008-08-24 sunday
2008-08-25 monday
2008-08-26 tuesday
2008-08-27 Wednesday
2008-08-28 thursday
2008-08-29 friday
2008-08-30 saturday
2008-08-31 sunday
2008-09-01 monday
2008-09-02 tuesday
2008-09-03 Wednesday
2008-09-04 thursday
2008-09-05 friday
2008-09-06 saturday

————————————————————————–

Class Variable Code 15:

class Second
puts @@a=34
def sec
puts @@a=66
end
end

class Check < Second
@@a=58
def one
@@a=34
end
end
c=Check.new()
puts c.one
puts c.sec

Output:

34
34
66
nil

————————————————————————–

Cheat — Ruby Gem

July 8, 2008

Cheat:

Very useful to view cheat sheet of like following things….

association_methods
asunit
authorizenet
autotest
averylongnamethatwecanfind
awk

Installation:

gem install cheat

How to use:

cmd prompt> cheat sheets

It gives lot of outputs. You are able to view all those cheat sheets from command prompt

Ex.

C:\>cheat migrations
migrations:
Methods:
create_table(name, options)
drop_table(name)
rename_table(old_name, new_name)
add_column(table_name, column_name, type, options)
rename_column(table_name, column_name, new_column_name)
change_column(table_name, column_name, type, options)
remove_column(table_name, column_name)
add_index(table_name, column_name, index_type)
remove_index(table_name, column_name)

Available Column Types:
* integer
* float
* datetime
* date
* timestamp
* time
* text
* string
* binary
* boolean
* decimal :precision, :scale

Valid Column Options:
* limit
* null (i.e. “:null => false” implies NOT NULL)
* default (to specify default values)
* :decimal, :precision => 8, :scale => 3

Rake Tasks:
rake db:schema:dump: run after you create a model to capture the schema.rb
rake db:schema:import: import the schema file into the current database (on
error, check if your schema.rb has “:force => true” on the create table
statements
./script/generate migration MigrationName: generate a new migration with a
new ‘highest’ version (run ‘./script/generate migration’ for this info at
your fingertips)
rake db:migrate: migrate your current database to the most recent version
rake db:migrate VERSION=5: migrate your current database to a specific
version (in this case, version 5)
rake db:rollback: migrate down one migration
rake db:rollback STEP=3: migrate down three migrations
rake db:migrate RAILS_ENV=production: migrate your production database

SQL:
Queries can be executed directly:
execute ‘ALTER TABLE researchers ADD CONSTRAINT fk_researchers_departments
FOREIGN KEY ( department_id ) REFERENCES departments( id )’

Example Migration:
class UpdateUsersAndCreateProducts < ActiveRecord::Migration
def self.up
rename_column “users”, “password”, “hashed_password”
remove_column “users”, “email”

User.reset_column_information
User.find(:all).each{|u| #do something with u}

create_table “products”, :force => true do |t|
t.column “name”, :text
t.column “description”, :text
t.column “price”, :decimal, :precision => 9, :scale => 2
end

#the rails 2.0 way:
create_table :people do |t|
t.integer :account_id
t.string  :first_name, :last_name, :null => false
t.text    :description
t.timestamps
end
end

def self.down
rename_column “users”, “hashed_password”, “password”
add_column “users”, “email”, :string
drop_table “products”
end
end

Find Highest version:
script/runner “puts ActiveRecord::Migrator.current_version”

C:\>

For more details,

http://cheat.errtheblog.com/

http://errtheblog.com/posts/21-cheat

Permutation – Ruby

July 7, 2008

Permutation:

This class has a dual purpose: It can be used to create permutations of a given size and to do some simple computations with/on permutations.

The instances of this class don’t require much memory because they don’t include the permutation as a data structure. They only save the information necessary to create the permutation if asked to do so.

STEP1: In case you are using Ruby 1.8.6 and previous versions then

Installation:

The library can be installed via rubygems:

c:\gem install permutation

Sample code:

require ‘Permutation’
perm = Permutation.new(3)
perm.map { |p| p p.value }
colors = [:r, :g, :b]
perm.map { |p| p p.project(colors) }
string = “abc”
perm.map { |p| p p.project(string) }

Output:

[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
[:r, :g, :b]
[:r, :b, :g]
[:g, :r, :b]
[:g, :b, :r]
[:b, :r, :g]
[:b, :g, :r]
“abc”
“acb”
“bac”
“bca”
“cab”
“cba”

STEP 2:

If you are using Ruby 1.8.7 and above then no need to install the gem.

CODE:

[1,2,3].permutation(3){|x| p x}

Output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

file concept in ruby

May 6, 2008

File concept in ruby:

Ruby program
**********

full= File.open(“raveendran.txt”)
phrase=["phrase1","phrase2","phrase3"]
count=0
full.each do |line|
first=[]
first=line.split(/\|/)
first.each do |single|
sub=single.strip!
main = (sub).to_s + ” “+(phrase [count]).to_s
puts main
count+=1
end
end

***********************************
raveendran.txt
******

item1 | item2 | item3 | item4 |
item11 | item21 | item31 | item41 |
item12 | item23 | item34 | item45 |
item13 | item23 | item33 | item43 |
item14 | item24 | item34 | item44 |
***********************************
Output
******

>ruby file.rb
item1 phrase1
item2 phrase2
item3 phrase3
item4

item11
item21
item31
item41

item12
item23
item34
item45

item13
item23
item33
item43

item14
item24
item34
item44
>Exit code: 0
*********************************

Regards,

P.Raveendran

while and until in Ruby

August 19, 2007

Using while and until:

1.upto(5) { |raveendran| puts raveendran}

output:

1
2
3
4
5

However, it’s possible to loop code in other ways. while and until allow you to loop
code based on the result of a comparison made on each loop:

x = 1
while x < 100
puts x
x = x * 2
end

output:
1
2
4
8
16
32
64

The same output using UNTIL:

x = 1
until x > 99
puts x
x = x * 2
end

It’s also possible to use while and until in a single line setting, as with if and unless:
i = 1
i = i * 2 until i > 1000
puts i
output:

1024