Today i have read next 4 chapters(5-6-7-8) from the book and I wanted to share few important quotations i found from these chapters.
Monday i will continue updating this ruby series with next 3 chapters.
1) Exponentiation (raising to a power) is done with the ** operator as in older languages such as BASIC and FORTRAN. It obeys the "normal" mathematical laws of exponentiation.
a = 64**2 # 4096
b = 64**0.5 # 8.0
c = 64**0 # 1
d = 64**-1 # 0.015625
2) If you want to round a floating point value to an integer, the method round will do the trick
Sometimes we want to round not to an integer but to a specific number of decimal places. In this case, we could use sprintf (which knows how to round) and eval to do this:
pi = 3.1415926535
pi6 = eval(sprintf("%8.6f",pi)) # 3.141593
3) Formatting Numbers for Output
To output numbers in a specific format, you can use the printf method in the Kernel module. It is virtually identical to its C counterpart. For more information, see the documentation for the printf method.
4) A Vector is in effect a special one-dimensional matrix. It can be created with the [] or elements methods; the first takes an expanded array, and the latter takes an unexpanded array and an optional copy parameter (which defaults to true).
arr = [2,3,4,5]
v1 = Vector[*arr] # Vector[2,3,4,5]
v2 = Vector.elements(arr) # Vector[2,3,4,5]
v3 = Vector.elements(arr,false) # Vector[2,3,4,5]
arr[2] = 7 # v3 is now Vector[2,3,7,5]
I struggled a bit trying to run Vector class in ruby and finally succeded thanks to google that we need to use this require statement above the class before using it.
require 'matrix'
5) The Kernel method rand returns a pseudorandom floating point number x such that x>=0.0 and x<1.0. For example (note yours will vary)
a = rand # 0.6279091137
6) Caching Functions with memoize
Suppose you have a computationally expensive mathematical function that will be called repeatedly in the course of execution. If speed is critical and you can afford to sacrifice a little memory, it may be effective to store the function results in a table and look them up. This makes the implicit assumption that the function will likely be called more than once with the same parameters; we are simply avoiding "throwing away" an expensive calculation only to redo it later on. This technique is sometimes called memoizing, hence the name of the memoize library.
Please remember that This is not part of the standard library, so you'll have to install it.
Example:
require 'memoize'
include Memoize
def zeta(x,y,z)
lim = 0.0001
gen = 0
loop do
gen += 1
p,q = x + y/2.0, z + y/2.0
x1, y1, z1 = p*p*1.0, 2*p*q*1.0, q*q*0.9
sum = x1 + y1 + z1
x1 /= sum
y1 /= sum
z1 /= sum
delta = [[x1,x],[y1,y],[z1,z]]
break if delta.all? {|a,b| (a-b).abs < lim }
x,y,z = x1,y1,z1
end
gen
end
g1 = zeta(0.8,0.1,0.1)
memoize(:zeta) # store table in memory
g2 = zeta(0.8,0.1,0.1)
memoize(:zeta,"z.cache") # store table on disk
g3 = zeta(0.8,0.1,0.1)
7) A symbol in Ruby is an instance of the class Symbol. The syntax is simple in the typical case: a colon followed by an identifier.
A symbol is like a string in that it corresponds to a sequence of characters. It is unlike a string in that each symbol has only one instance (just as a Fixnum works). Therefore, there is a memory or performance issue to be aware of. For example, in the following code, the string "foo" is stored as three separate objects in memory, but the symbol :foo is stored as a single object (referenced more than once):
array = ["foo", "foo", "foo", :foo, :foo, :foo]
Probably the best known use of symbols is in defining attributes on a class:
class MyClass
attr_reader :alpha, :beta
attr_writer :gamma, :delta
attr_accessor :epsilon
# ...
end
Converting to/from Symbols
Strings and symbols can be freely interconverted with the to_str and to_sym methods:
a = "foobar"
b = :foobar
a == b.to_str # true
b == a.to_sym # true
If you're doing metaprogramming, the following method might prove useful sometimes.
class Symbol
def +(other)
(self.to_s + other.to_s).to_sym
end
end
8) Iterating Over Ranges
Typically it's possible to iterate over a range. For this to work, the class of the endpoints must define a meaningful succ method.
(3..6).each {|x| puts x } # prints four lines
# (parens are necessary)
9) When we convert a range to an array, the interpreter simply applies succ repeatedly until the end is reached, appending each item onto an array that is returned:
r = 3..12
arr = r.to_a # [3,4,5,6,7,8,9,10,11,12]
10) Determining the Current Time
The most fundamental problem in time/date manipulation is to answer the question: What is the time and date right now? In Ruby, when we create a Time object with no parameters, it is set to the current date and time.
t0 = Time.new
11) The mktime method creates a new Time object based on the parameters passed to it. These time units are given in reverse from longest to shortest: year, month, day, hours, minutes, seconds, microseconds. All but the year are optional; they default to the lowest possible value. The microseconds may be ignored on many architectures. The hours must be between 0 and 23 (that is, a 24-hour clock).
t1 = Time.mktime(2001) # January 1, 2001 at 0:00:00
t2 = Time.mktime(2001,3)
t3 = Time.mktime(2001,3,15)
t4 = Time.mktime(2001,3,15,21)
t5 = Time.mktime(2001,3,15,21,30)
t6 = Time.mktime(2001,3,15,21,30,15) # March 15, 2001 9:30:15 pm
11) Finding the Day of the Year
we can use the yday method:
t = Time.now
day = t.yday # 315
12) A date and time can be formatted as a string in many different ways because of abbreviations, varying punctuation, different orderings, and so on. Because of the various ways of formatting, writing code to decipher such a character string can be daunting. Consider these examples:
s1 = "9/13/98 2:15am"
Fortunately, much of the work has already been done for us. The ParseDate module has a single class of the same name, which has a single method called parsedate. This method returns an array of elements in this order: year, month, day, hour, minute, second, time zone, day of week. Any fields that cannot be determined are returned as nil values.
require "parsedate.rb"
include ParseDate
p parsedate(s1) # [98, 9, 13, 2, 15, nil, nil, nil]
13) Iterating Over a Hash
The Hash class has the standard iterator each as is to be expected. It also has each_key, each_pair, and each_value. (each_pair is an alias for each.)
{"a"=>3,"b"=>2}.each do |key, val|
print val, " from ", key, "; " # 3 from a; 2 from b;
end
Inverting a hash in Ruby is trivial with the invert method:
a = {"fred"=>"555-1122","jane"=>"555-7779"}
b = a.invert
b["555-7779"] # "jane"
14) Creating a Hash from an Array
The easiest way to do this is to remember the bracket notation for creating hashes. This works if the array has an even number of elements.
array = [2, 3, 4, 5, 6, 7]
hash = Hash[*array]
# hash is now: {2=>3, 4=>5, 6=>7}
15) The inject Method
The inject method comes to Ruby via Smalltalk (and was introduced in Ruby 1.8).
This method relies on the fact that frequently we will iterate through a list and "accumulate" a result that changes as we iterate. The most common example, of course, would be finding the sum of a list of numbers. Whatever the operation, there is usually an "accumulator" of some kind (for which we supply an initial value) and a function or operation we apply (represented in Ruby as a block).
For a trivial example or two, suppose that we have this array of numbers and we want to find the sum of all of them:
nums = [3,5,7,9,11,13]
sum = nums.inject(0) {|x,n| x+n }
Note how we start with an accumulator of 0 (the "addition identity"). Then the block gets the current accumulated value and the current value from the list passed in. In each case, the block takes the previous sum and adds the current item to it.
Obviously, this is equivalent to the following piece of code:
sum = 0
nums.each {|n| sum += n }
16) The partition Method
When partition is called and passed a block, the block is evaluated for each element in the collection. The truth value of each result is then evaluated, and a pair of arrays (inside another array) is returned. All the elements resulting in true go in the first array; the others go in the second.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_even = nums.partition {|x| x % 2 == 1 }
# [[1,3,5,7,9],[2,3,4,6,8]]
under5 = nums.partition {|x| x < 5 }
# [[1,2,3,4],[5,6,7,8,9]]
squares = nums.partition {|x| Math.sqrt(x).to_i**2 == x }
# [[1,4,9],[2,3,5,6,7,8]]
17) Iterating by Groups
There might be times we want to grab these in pairs or triples or some other quantity.
The iterator each_slice takes a parameter n and iterates over that many elements at a time. (To use this, we need the enumerator library.) If there are not enough items left to form a slice, that slice will be smaller in size.
require 'enumerator'
arr = [1,2,3,4,5,6,7,8,9,10]
arr.each_slice(3) do |triple|
puts triple.join(",")
end
# Output:
# 1,2,3
# 4,5,6
# 7,8,9
# 10
18) Converting to Arrays or Sets
Every enumerable can in theory be converted trivially to an array (by using to_a). For example, a hash results in a nested array of pairs:
hash = {1=>2, 3=>4, 5=>6}
arr = hash.to_a # [[5, 6], [1, 2], [3, 4]]
The method enTRies is an alias for the to_a method.
If the set library has been required, there will also be a to_set method that works as expected.
require 'set'
hash = {1=>2, 3=>4, 5=>6}
set = hash.to_set # #
About the Author
Hal Fulton has two degrees in computer science from the University of Mississippi. He taught computer science for four years at the community college level before moving to Austin, Texas, for a series of contracts (mainly at IBM Austin). He has worked for more than 15 years with various forms of UNIX, including AIX, Solaris, and Linux. He was first exposed to Ruby in 1999, and in 2001 he began work on the first edition of this book, which was the second Ruby book in the English language. He has attended six Ruby conferences and has given presentations at four of those, including the first European Ruby Conference in Karlsruhe, Germany. He currently works at Broadwing Communications in Austin, Texas, working on a large data warehouse and related telecom applications. He works daily with C++, Oracle, and of course, Ruby.
Hal is still active daily on the Ruby mailing list and IRC channel, and has several Ruby projects in progress. He is a member of the ACM and the IEEE Computer Society. In his personal life, he enjoys music, reading, writing, art, and photography. He is a member of the Mars Society and is a space enthusiast who would love to go into space before he dies. He lives in Austin, Texas.
6 comments:
[b][url=http://www.bestlouisvuittonbags.co.uk/]louis vuitton handbags[/url][/b] In 1854, he commenced her or his first preserve all the way through Paris then was in Liverpool thirty-one years afterwards. These 2 stores essentially was making yearly gross profits related with affiliated to $10 k from the software of 1977. This enhance all by means of track record involving Louis Vuitton wound up presently currently being fantastic and bringing on this specific expanding establish to become lots a lot more sizeable.
[b][url=http://www.louisvuittonhandbagsu.com/]Louis Vuitton purses[/url][/b] Some samples of severe sports incorporate sizzling dogging (snow skiing off a ramp and executing flips), skateboarding with a U formed study course, bungee leaping, base leaping etc. Many people that like sports activities abide by their favored workforce. This staff is often is from their space.
[b][url=http://www.uggsclearancemall.co.uk/]ugg uk[/url][/b] And hence, 1 unique sociaddictionsl get blogging psscorliss? Without doubt, Mothers and fathers believe that, The real heads, And so are previously embodied in youngsters as well as the youthful generation, Regardless of regardless of whether incredible, wrong. Louis Vuitton includes a extended heritage as similar to it is really really mobile phone. The place paleo is usually beachfront entrance supplies completely absolutely free features are all over the myriad, Presenting the idea on the subject of numerous paleo food stuff..
[b][url=http://www.uggsclearancemall.co.uk/]uggs clearance[/url][/b] The initial factor that you will need to cope with after you opt to incorporate affiliate internet marketing in your home enterprise is the fact some merchant web pages are somewhat difficult to navigate. Shoppers tend to be turn off from acquiring their merchandise since it is difficult to search via. Generally occasions, merchant sites, which can be tough to navigate, also have problematic payment technique that folks who will not possess the persistence to cope with complications may perhaps just depart the site without having obtaining whatsoever.
[b][url=http://www.uggsbootsoutletmall.co.uk/]uggs boots outlet[/url][/b] For females, it is so terrific that they don't really need to annoy at ways to get the trend and function together. They will catch the vogue craze exactly from the Hermes environment. You are going to uncover just one to complement your disposition or any motive, and be envious by other females for your elegant tone.
top [url=http://www.001casino.com/]online casinos[/url] brake the latest [url=http://www.casinolasvegass.com/]online casino[/url] unshackled no consign perk at the foremost [url=http://www.baywatchcasino.com/]online casinos
[/url].
The number 1 rule [url=http://www.germanylovelv.com/]Louis Vuitton kopierte Tasche kaufen[/url]
remember about marketing anF aFvertising success is its normally concerning the prospect anF not about you. As superb while you plus your company may possibly be the prospect coulF treatment les[url=http://www.germanylovelv.com/]Louis Vuitton kopierte Tasche kaufen[/url]
They only want [url=http://www.germanylovelv.com/]louis vuitton knolckoffs[/url]
know that which you can Fo [url=http://www.germanylovelv.com/]Louis Vuitton Outlet[/url]
solve their issue, boost their problem, or give them the things they want.
While in the past couple oF years, POF has generateF a huge buzz in the FielF, promising [url=http://www.germanylovelv.com/]louis vuitton knolckoffs[/url]
proviFe the keys [url=http://www.germanylovelv.com/]Louis Vuitton kopierte Tasche kaufen[/url]
the serious publishing kingFom For all those authors heretoFore lockeF out oF the game anF other loFty claimhttp://www.germanylovelv.com/
Not really. Remember, POF isnt some miracle or a publishing revolution; its just a printing technology, nothing more.
PerFectly, you'll be able to absolutely crack this conFerence. Why not test new protect resources? FeciFe on From Fistinctive sorts oF paper - you'll FinF corrugateF types, textureF, carFboarF anF many other beautiFul resources that may make your booklet covers get noticeF. Bear in minF, in the event you think oF a wonFerFul go over, you generate an sense that shoulF last.
[url=http://longchampsoldesk.fotopages.com/]sac longchamps[/url] See diagram A to tie a knot at the end of the necklace Mulberry Classic Natural Leather Messenger Bag Black for Men,Welcome to Mulberry Outlet Store,save up to 50% and begin to string your beads. Go ahead, decorate your pig bank with the enclosed red, blue and yellow paints, and he will come alive. Many of the items are already put together for you to decorate with stickers or paint.
[url=http://longchamppaschers.jigsy.com/]sac longchamp[/url] Btw, as much as I would love to argue against it, I can't really argue with Kill Bill winning the top spot. I could point out a few bad-ass sword fights from some classics but Quentin made sure to topple them all with his Crazy 88 fight sequence. The black and white aspect may be obvious for dodging the MPAA but I Highly Appreciated Mulberry Women's Bayswater Trimming Oxford & Leather Tote Bag Black still think it actually works better from an aesthetic outlook.
[url=http://longchamppliagea.busythumbs.com/]sac longchamps[/url] Using way too many chemicals excessively will guide to a build up that could compromise this integrity with the materials. The truth is, the type of content itself is dependent upon how often it is best to clean the bag and what sort of technique you should utilize to clean it. And for all of the Do-it-yourself fashionistas, never attempt to remove a substantial stain alone. With the credit crunch upon us, the female dilemma is how to stay fashionable on a budget. You can do so by trying out some fashion tips that let you show your fashion sense but also keeps you within a budget. Believe it or not, to be fashionable, you need not spend a fortune; you can be fashionable even within a limited budget.. Just like with some Vera Bradley patterns, everyone may be appalled initially, Vogue Mulberry Women's Smaller Bayswater Leather Shoulder Black Bag sale well, Shop Our New Autumn/Winter Styles to get the latest look but the more they will notice it the more they come to be used to it and at last adore those quilted fabric designs. They have understood that these aren't only storage units that keep items, they are really fashion accessories to outfits to boot. Of course, if the handbag isn't going to match the dress, then it is just not going to do the trick..
Where here against authority
Yes you are talented
It is possible to speak infinitely on this question.
I will know, many thanks for an explanation.
Very useful question
[url=http://shenenmaoyiqwe.bravesites.com/][b]michael kors outlet online[/b][/url]
[url=http://03jdela.dhpreview.devhub.com/][b]michael kors outlet online[/b][/url]
[url=http://shenenmaoyik.futblog.com.br/][b]michael kors outlet online[/b][/url]
[url=http://shenenmaoyipp.webs.com/][b]michael kors outlet online[/b][/url]
[url=http://michaelkorsoutlet0.freeblog.hu/][b]michael kors outlet online[/b][/url]
Albert E. Mercer Jr.
Relatives and friends are advised of the passing of Albert E. Mercer, affectionately known as Bay-toe, St. Pauli [url=http://www.agoshow.net/Brewers-8-Braun-Black-2011-All-Star-Jerseys-105/]Brewers 8 Braun Black 2011 All Star Jerseys[/url] Girl and Mr. Dick the ice cream man.
He was a native of Tortola, who resided and contributed positively to the Virgin Islands for more than 50 years. He was instrumental in the formation of [url=http://www.agoshow.net/Yankees-52-CC-Sabathia-White-2010-All-Star-Jerseys-62/]Yankees 52 CC Sabathia White 2010 All Star Jerseys[/url] Islander Taxi, Inc., and many other business ventures.
The first viewing is from 5 to 7 p.m. Friday at Scatliffe Memorial Chapel in Road Town, Tortola.
The second viewing is from 6 to 7:30 p.m. Monday at Turnbull's Funeral Home Chapel on St. Thomas.
The third and final viewing is at 8 a.m. Tuesday at Wesley Methodist Church in Tutu, with the funeral at 10 a.m. at the same location.
Burial will be at Eastern Cemetery.
He is survived by his wife, Dorothy Mercer; five children, Annette Mercer-Grant, Moses, Harriet, Jeffrey and Bennett Mercer; three stepchildren, Olivine Abraham-Pinkney, Heidi Daley-Vialet and Herdina Daley; two brothers, Rufus and Akil Mercer; two sisters, Naomi Mercer-Donovan and Shinika Mercer; 19 grandchildren; 11 great-grandchildren; special family members, Blacks and Ava; special friends, the Coki Point Posse; other family and friends too numerous to mention.
The immediate family will [url=http://www.agoshow.net/Red-Sox-31-Jon-Lester-Home-Cool-Base-White-2010-All-Star-Jerseys-82/]Red Sox 31 Jon Lester Home Cool Base White 2010 All Star Jerseys[/url] wear shades of purple, but knowing our beloved Albert as a man who celebrated [url=http://www.agoshow.net/2009-All-Star-Milwaukee-Brewers-28-Prince-Fielder-Red-Jerseys-19/]2009 All Star Milwaukee Brewers 28 Prince Fielder Red Jerseys[/url] life to the fullest, his survivors request that you wear festive colors. [url=http://www.agoshow.net/Mets-7-Jose-Reyes-blue-2010-All-Star-Jerseys-41/]Mets 7 Jose Reyes blue 2010 All Star Jerseys[/url]
Arrangements are by Scatliffe Memorial in Tortola and Turnbull's Funeral Home on St. Thomas.
Please send booklet tributes to annettepgrant@yahoo.com or call 779-6486 no later than Friday.
- Obituary written by the family..
[url=]more[/url]
Post a Comment