[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How to Iterate over nested Hashes ?

Dinesh Dinesh

3/24/2006 9:22:00 AM

Hi,

I'm new to Ruby. I want to know how to iterate over a nested hash as
below.

*****************************************************************************
testhash = {

"recipeKey"=>{"title"=>"RailsBook", "category_id"=>"1",
"description"=>"This is a book about Rails", "instructions"=>"Read It"}

}
testhash.each {|key, value| print key, " value is : ", value, "\n" }

Here is the output i get..

==> recipeKey value is : titleRailsBookdescriptionThis is a book about
Railscategory_id1instructionsRead It
*****************************************************************************

As per the input "testhash", the value itself is a hash rt with keys as
"title","category_id","description" and "instructions"? Now how to get
these values as a key/value pair ??

If we apply "eash" operator for "testhash", the values are getting
printed "continously string" as shown above???, is this the expected
behaviour?

I tried to assign this value into a "new hash" variable and when i
applied "each" on this varibale, it said "each" varible undefined, the
reason may be that the value which i assinged is not a hash? so wanted
to know how to iterate the above nested hash ? Please help me out.

Thank You..

--
Posted via http://www.ruby-....


7 Answers

Robert Dober

3/24/2006 9:40:00 AM

0

Something like this might work

---------------------------------- 8< --------------------------
#!/usr/bin/env ruby

testhash = {
:outside => 1,
"recipeKey"=>{"title"=>"RailsBook", "category_id"=>"1",
"description"=>"This is a book about Rails", "instructions"=>"Read It",
"author" => { :name => "Robert", :email => "<robert.dober@gmail.com>" }
},
:out_again => true

}

def traverse( aHash, level = 0 )
aHash.each do
|k, v|
puts "%s%s:%s" % [ " " *level, k,
v.kind_of?(Hash) ? traverse( v, level + 1) : v
]
end # do
""
end # def traverse(

traverse testhash
---------------------------------- >8 --------------------------

hope that helps

Robert
On 3/24/06, Dinesh Dinesh <u_dinesh@yahoo.com> wrote:
>
> Hi,
>
> I'm new to Ruby. I want to know how to iterate over a nested hash as
> below.
>
>
> *****************************************************************************
> testhash = {
>
> "recipeKey"=>{"title"=>"RailsBook", "category_id"=>"1",
> "description"=>"This is a book about Rails", "instructions"=>"Read It"}
>
> }
> testhash.each {|key, value| print key, " value is : ", value, "\n" }
>
> Here is the output i get..
>
> ==> recipeKey value is : titleRailsBookdescriptionThis is a book about
> Railscategory_id1instructionsRead It
>
> *****************************************************************************
>
> As per the input "testhash", the value itself is a hash rt with keys as
> "title","category_id","description" and "instructions"? Now how to get
> these values as a key/value pair ??
>
> If we apply "eash" operator for "testhash", the values are getting
> printed "continously string" as shown above???, is this the expected
> behaviour?
>
> I tried to assign this value into a "new hash" variable and when i
> applied "each" on this varibale, it said "each" varible undefined, the
> reason may be that the value which i assinged is not a hash? so wanted
> to know how to iterate the above nested hash ? Please help me out.
>
> Thank You..
>
> --
> Posted via http://www.ruby-....
>
>


--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein

Robert Klemme

3/24/2006 9:42:00 AM

0

Dinesh Dinesh wrote:
> Hi,
>
> I'm new to Ruby. I want to know how to iterate over a nested hash as
> below.
>
> *****************************************************************************
> testhash = {
>
> "recipeKey"=>{"title"=>"RailsBook", "category_id"=>"1",
> "description"=>"This is a book about Rails", "instructions"=>"Read It"}
>
> }
> testhash.each {|key, value| print key, " value is : ", value, "\n" }
>
> Here is the output i get..
>
> ==> recipeKey value is : titleRailsBookdescriptionThis is a book about
> Railscategory_id1instructionsRead It
> *****************************************************************************
>
> As per the input "testhash", the value itself is a hash rt with keys as
> "title","category_id","description" and "instructions"? Now how to get
> these values as a key/value pair ??
>
> If we apply "eash" operator for "testhash", the values are getting
> printed "continously string" as shown above???, is this the expected
> behaviour?

Yes, it's the result of a hash converted to string.

> I tried to assign this value into a "new hash" variable and when i
> applied "each" on this varibale, it said "each" varible undefined, the
> reason may be that the value which i assinged is not a hash?

"each" is a method not a variable.

> so wanted
> to know how to iterate the above nested hash ? Please help me out.

First of all you should describe what you want to see during the
iteration. Do you only want to see key value pairs of nested hashes?
Do you want to see key1,key2,value?

If you just want to print the whole Hash you can use pp:

>> require 'pp'
=> true
>> testhash = {
....
>> pp testhash
{"recipeKey"=>
{"title"=>"RailsBook",
"description"=>"This is a book about Rails",
"category_id"=>"1",
"instructions"=>"Read It"}}

Kind regards

robert

Dinesh Dinesh

3/24/2006 10:28:00 AM

0

Hi Robert,

Thank a LOT for the quick reply. Sorry for not making it clear when i
have posted it.

What i was looking is, if the "value" is a hash, then i want to assign
this value to another hash variable, so that upon iterating that hash
variable i should see the key/value pairs of this new value.

In our case even though the "value" was a hash i think while iterating
it gets converted to string and it is printing as "continious string".

I was thinking that if i create a new hash and assign the "value" (which
is a hash) to this new hash, then i can iterate it. But what i feel is
as you have mentioned we have to use some thing like "traverse" which
you have written to manipulate it.

So Is there any built-in "methods" to take care of situations like this
(nested - nested hash) than writing our own "traverse" methods like this
?

Again thanks for your quick and kind reply.

Dinesh

Robert Klemme wrote:
> Dinesh Dinesh wrote:
>>
>> "title","category_id","description" and "instructions"? Now how to get
>> these values as a key/value pair ??
>>
>> If we apply "eash" operator for "testhash", the values are getting
>> printed "continously string" as shown above???, is this the expected
>> behaviour?
>
> Yes, it's the result of a hash converted to string.
>
>> I tried to assign this value into a "new hash" variable and when i
>> applied "each" on this varibale, it said "each" varible undefined, the
>> reason may be that the value which i assinged is not a hash?
>
> "each" is a method not a variable.
>
> > so wanted
>> to know how to iterate the above nested hash ? Please help me out.
>
> First of all you should describe what you want to see during the
> iteration. Do you only want to see key value pairs of nested hashes?
> Do you want to see key1,key2,value?
>
> If you just want to print the whole Hash you can use pp:
>
> >> require 'pp'
> => true
> >> testhash = {
> ....
> >> pp testhash
> {"recipeKey"=>
> {"title"=>"RailsBook",
> "description"=>"This is a book about Rails",
> "category_id"=>"1",
> "instructions"=>"Read It"}}
>
> Kind regards
>
> robert


--
Posted via http://www.ruby-....


Robert Klemme

3/24/2006 1:09:00 PM

0

Dinesh Umanath wrote:

Please don't top post.

> Thank a LOT for the quick reply. Sorry for not making it clear when i
> have posted it.
>
> What i was looking is, if the "value" is a hash, then i want to assign
> this value to another hash variable, so that upon iterating that hash
> variable i should see the key/value pairs of this new value.
>
> In our case even though the "value" was a hash i think while iterating
> it gets converted to string and it is printing as "continious string".

No, it is converted during printing.

> I was thinking that if i create a new hash and assign the "value" (which
> is a hash) to this new hash, then i can iterate it. But what i feel is
> as you have mentioned we have to use some thing like "traverse" which
> you have written to manipulate it.
>
> So Is there any built-in "methods" to take care of situations like this
> (nested - nested hash) than writing our own "traverse" methods like this
> ?

No. Because there are plenty equally useful ways to do it. In some
scenarios it might be required to see the whole path of keys in others
the recursion depth is fixed...

It really depends on what you want to do.

Regards

robert

acoustic

9/30/2012 9:05:00 AM

0

In article <35cab062-7072-4a0f-bc93-c72d4c1a92c8@ro10g2000pbc.googlegroups.com>,
rst9 <rst9wxyz@yahoo.com> wrote:
>http://www.wantchinatimes.com/news-subclass-cnt.aspx?id=20120927000082&am...
>
>Zhang Zheng, commander of China's first aircraft carrier
>Staff Reporter 2012-09-27 15:49 (GMT+8)
>
>Zhang Zheng is the first commander of the PLA's new aircraft carrier.
>(Photo/Xinhua)
>
>Senior Colonel Zhang Zheng has officially been named commander of the
>Liaoning, China's first aircraft carrier, reports the Shanghai-based
>Oriental Morning Post.
>
>Zhang was born into a military family at Changxing, Zhejiang province
>in 1969. After graduating from Shanghai's Jiao Tong University in
>1990, he joined the People's Liberation Army Navy and began his
>service at the headquarters of the East Sea Fleet.
>
>With a strong ambition to become a naval captain, Zhang gave up
>opportunities to study abroad or go into business.
>
>"I will not get married until I become the captain of a ship," Zhang
>once told an admiral when he was at the Dalian Naval Academy.
>
>Zhang later became an executive officer after receiving a master's
>degree from the academy in 1997.
>
>Zhang was never a pilot, but he did become the captain of a frigate
>before taking control of the country's largest guided missile
>destroyer at the time. Between July 2001 and August 2003, Zhang was
>sent to the United Kingdom to study at the Defense Language Institute
>and the British Joint Services Command and Staff College. Ninety-eight
>percent of the crew aboard the Liaoning are graduates of the college.
>
>Being appointed the first captain of Liaoning, which was converted
>from the ex-Ukranian Varyag, has made Zhang a national hero,
>especially among his old classmates at Jiao Tong University in
>Shanghai.
>
>"I never knew he became a captain until I watched the news," said one
>of his classmates. "He never came to our reunion, probably because he
>has a special job."
>
>One of Zhang's teachers from the First Middle School of Dinghai told
>reporters that Zhang was a very quiet student who always helped others
>in need.
>
>Xie Jingzu, a high school classmate, said Zhang once stopped him one
>from cheating in an exam. He told me that it was for my own good, Xie
>said.
>
>"People are more currently important than the equipment," said PLA
>General Luo Yuan when discussing Zhang and his crew. "Some of the
>1,000 personnel are the top graduates from our naval academies while
>others are professional crew members transferred to Liaoning from
>other combat vessels."
>
>Zhang's greatest challenge will be when carrier-based aircraft begin
>to land aboard the Liaoning, and it will take a lot of courage and
>determination to complete his duty, according to Qiao Liang, a retired
>colonel from the PLA Air Force.
>
>Qiao, who co-authored the book Unrestricted Warfare, said, "Zhang must
>have enough culture, military and psychological qualities to fulfill
>his job."
>

Informative. Jiao Tong University has a great reputation as an
engineering school in China since the early 1900s. To appreciate this
perception, all one need to know is that after the Nationalists fled
to Taiwan in 1949, they set up a parallel campus called the National
Chiao Tong University, in Hsinchu, near Taipei. At the same time, the
PRC also multiplied the university into several campuses located not
only in Shanghai, but also in Xi'an and Beijing. It is easy to see
that first-class education is the foundation of the future of China.

lo yeeOn

rst9

9/30/2012 4:06:00 PM

0

On Sep 30, 2:04 am, acous...@panix.com (lo yeeOn) wrote:
> In article <35cab062-7072-4a0f-bc93-c72d4c1a9...@ro10g2000pbc.googlegroups.com>,
>
>
>
>
>
>
>
>
>
> rst9  <rst9w...@yahoo.com> wrote:
> >http://www.wantchinatimes.com/news-subclass-cnt.aspx?id=201.......
>
> >Zhang Zheng, commander of China's first aircraft carrier
> >Staff Reporter 2012-09-27 15:49 (GMT+8)
>
> >Zhang Zheng is the first commander of the PLA's new aircraft carrier.
> >(Photo/Xinhua)
>
> >Senior Colonel Zhang Zheng has officially been named commander of the
> >Liaoning, China's first aircraft carrier, reports the Shanghai-based
> >Oriental Morning Post.
>
> >Zhang was born into a military family at Changxing, Zhejiang province
> >in 1969. After graduating from Shanghai's Jiao Tong University in
> >1990, he joined the People's Liberation Army Navy and began his
> >service at the headquarters of the East Sea Fleet.
>
> >With a strong ambition to become a naval captain, Zhang gave up
> >opportunities to study abroad or go into business.
>
> >"I will not get married until I become the captain of a ship," Zhang
> >once told an admiral when he was at the Dalian Naval Academy.
>
> >Zhang later became an executive officer after receiving a master's
> >degree from the academy in 1997.
>
> >Zhang was never a pilot, but he did become the captain of a frigate
> >before taking control of the country's largest guided missile
> >destroyer at the time. Between July 2001 and August 2003, Zhang was
> >sent to the United Kingdom to study at the Defense Language Institute
> >and the British Joint Services Command and Staff College. Ninety-eight
> >percent of the crew aboard the Liaoning are graduates of the college.
>
> >Being appointed the first captain of Liaoning, which was converted
> >from the ex-Ukranian Varyag, has made Zhang a national hero,
> >especially among his old classmates at Jiao Tong University in
> >Shanghai.
>
> >"I never knew he became a captain until I watched the news," said one
> >of his classmates. "He never came to our reunion, probably because he
> >has a special job."
>
> >One of Zhang's teachers from the First Middle School of Dinghai told
> >reporters that Zhang was a very quiet student who always helped others
> >in need.
>
> >Xie Jingzu, a high school classmate, said Zhang once stopped him one
> >from cheating in an exam. He told me that it was for my own good, Xie
> >said.
>
> >"People are more currently important than the equipment," said PLA
> >General Luo Yuan when discussing Zhang and his crew. "Some of the
> >1,000 personnel are the top graduates from our naval academies while
> >others are professional crew members transferred to Liaoning from
> >other combat vessels."
>
> >Zhang's greatest challenge will be when carrier-based aircraft begin
> >to land aboard the Liaoning, and it will take a lot of courage and
> >determination to complete his duty, according to Qiao Liang, a retired
> >colonel from the PLA Air Force.
>
> >Qiao, who co-authored the book Unrestricted Warfare, said, "Zhang must
> >have enough culture, military and psychological qualities to fulfill
> >his job."
>
> Informative.  Jiao Tong University has a great reputation as an
> engineering school in China since the early 1900s.  To appreciate this
> perception, all one need to know is that after the Nationalists fled
> to Taiwan in 1949, they set up a parallel campus called the National
> Chiao Tong University, in Hsinchu, near Taipei.  At the same time, the
> PRC also multiplied the university into several campuses located not
> only in Shanghai, but also in Xi'an and Beijing.  It is easy to see
> that first-class education is the foundation of the future of China.
>
> lo yeeOn

"First-class education" depends on the individual, not the name of the
college or campus. I know people educated from MIT, Cal Tech,...
were just dummies, can't think for themselves.

rst9

10/1/2012 5:14:00 AM

0

On Sep 30, 7:52 pm, acous...@panix.com (lo yeeOn) wrote:
> In article <1d74a694-63fc-4f6e-bf0c-d4c2d94f0...@wm7g2000pbc.googlegroups..com>,
> >"First-class education" depends on the individual, not the name of the
> >college or campus.  I know people educated from MIT, Cal Tech,...
> >were just dummies, can't think for themselves.
>
> Beg to disagree!  Without a first-class educational environment,

"First-class education" does not mean an Ivy League name university or
beautiful campus buildings and laboratories. What it takes is
individual drives and curiosity to investigate and experiment.
Of course, it always help to have equipment and lab space to work.
Any university can provide all or most of the tools you need.

> I don't care how good the individuals are.

That is the main ingredient for success, individual drives and
curiosity to investigate.
People like Thomas Edison, George Washington Carver, Nikola Tesla,..
have proven it.

> It takes the right
> environment to grow a person with the right stuff.

An individual with curiosity and drives to investigate will make and
invent the tools he needed to succeed. Of course, it always help to
have them around.

> To think otherwise
> would be anti-materialistic, and therefore wishful thinking.

If you had read the background of people like Thomas Edison, George
Washington Carver, Nikola Tesla,..

You will find they basically made everything themselves.

All you need to succeed is personal drive and a desire to do
something.

>
> What China needs is a) a huge amount of investment in research and
> education -

Yes, I agree.

> investing in the right areas,

What is considered to be "the right areas"?

> like a neighborhood center
> every other block, equipped with oscilloscopes, digital lab stations,
> GPS devices, precision machine shops, and of course computers and
> audio-visual presentation rooms.

I think the above description is a lot of wasted capital equipment and
money.

I would suggest an agency to determine the viability of individual
research and help this individual along as to the ideas can be done
and tested. As long as he is making progress, continue to fund his
experiment.


> I've said it more than once before.

Yes, I read it before.

>
> We know that Japan invests a high percentage of its GDP on research
> and education and that has proven extremely valuable to Japan's
> national development.  Today, people often say that China still has
> not shown that it is capable of innovation.

People continue to believe Chinese are only good at rote learning.
But it's not true anymore. It's hard to break habit.

> Well, is it because China
> doesn't have what it takes, i.e., the people who can do something as
> brilliant as Galileo, Gauss, Tsiokovsky, Da Vinci, and other geniuses
> the Europeans have produced or because the Chinese people haven't had
> the right environment to grow in?

Human beings are all the same regardless of race or nationalities. It
was culture and history which make us different.

Now, the world has shrunk a lot since the last hundred years.
Cultures and societies have intermingled. We all think pretty much
the same today. We all have the same capability as everybody else.
China and the Chinese people have proven their abilities and
capabilities are just as good, if not better than others.

>
> I greatly admire the captain in your post.  It takes someone as
> dedicated as he has been to succeed.

Yes, it's indivodual drive to succeed.

> But tell me why is it that we
> don't see the likes of this captain in the pre-CCP days of China in
> the last several hundred years?

Culture and history. The name for China itself was an indication of
what the problem was, the "center country". The Chinese people
thought they were superior and looked down on other people.
Read about China/British protocol and messages transmitted from the
1790s - 1840s. China tried using reason with the British when the
British were ready for war.

> Tell me why there are so many
> successful atheletes,

Europeans made strength/war as part of life, while Chinese history
stressed on finesse/outsmart your opponents.

> musicians,

Every society has beautiful music. China has/had beautiful music.

> and women in aviation and even space
> travel today?

Blame Emperor Qianlung of the Qing Dynasty. He refused to accept the
British manufactured goods, saying "China has everything under
heaven. We have no use for your manufactured goods".

> Even the disabled excel in China today!  See the
> article below for what I'm talking about.

The disabled excel much much more in the Western World.

>
> I was deeply moved when I first read it.  And I am convinced it could
> happen only because today's China is not only well positioned to
> afford its people an unprecedented opportunity to live their lives to
> the fullest but also has the right moral fibre to make that
> opportunity a reality for anyone who wants to give it a try - not for
> the negative thinking people, though.  And that is compassion.
> Without compassion, without the government's sensitivity to its
> people's vital needs, China's success in the 2012 Paralympics would
> have never been a reality.  In comparing the numbers, it is important
> to remember that the United States outperformed in the 2012 Olympics
> by a significant margin over China.  So, the argument that China has a
> much larger population than the US doesn't explain its performance at
> the Parlaympics games.  It would require that there are more disabled
> children among every, say, 100 children, growing up in today's China
> than those among every 100 American children growing up.  There is no
> evidence to support that.  On the other hand, there is plenty of
> evidence to support this assessment from the US sports journalist Jim
> Ferstle.  He said, in reference to the US:
>
>   "It isn't a priority, they don't get the funding, they don't get
>    the attention and they aren't sold the same way the Olympics are,"
>
> Ruth Alexander's BBC article and Jim Ferstle's comments show to me
> beyond any doubt that today's China is run a compassionate government
> system which has its people's best interests at heart, even though it
> is still developing in many areas.  And that is, in my view, their
> ultimate justification for maintain a socialist system.  By contrast,
> all the talk of freedom and democracy, a capitalist society today in
> America means that most people are at the mercy of the few who have.
>
> That is not freedom.  That is not democracy.  Any talk of freedom and
> democracy is just hot air, signifying nothing actual!
>
> lo yeeOn
>
> In which countries did Paralympians outperform Olympians?
> By Ruth Alexander BBC News
> 10 September 2012 Last updated at 20:02 ET
>
> http://www.bbc.co.uk/news/magazin...
>
> The United States topped the Olympic Games league table with 46 gold
> medals, but they won about a third fewer in the Paralympics - 31,
> placing them outside the top five, in sixth place.
>
> This performance is quite a puzzle, because the US has two of the big
> vital ingredients for success - wealth and a large population.
>
> Population and Gross Domestic Product (GDP) explain about 53% of a
> nation's a success in the Olympic Games, and more than 60% in the
> Paralympic Games, according to the calculations of Simon Shibli, a
> professor of sport management at Sheffield Hallam University in the
> UK.
>
> A big population means a big pool of talent to fish from, and wealth
> means good healthcare and the money to spend on sports training and
> facilities.
>
> But a further puzzle is that, if you look at the historical figures,
> you see the US is actually top of the all-time Paralympic gold medal
> league table.
>
> China 95   38   237*  (best performer at the Paralympics 2012)
>
> USA   31   46   696*  (ranked sixth at the Paralympics 2012, even
>                        though it has the highest historical total)
>
> GB    34   29   519*  (ranked third, after Russia)
>
> IPC to scrutinise future media deals with the US and other
> `under-performing' Paralympic nations
>
> Mick Fealty, Tue 11 September 2012, 12:01pm
>
> http://sluggerotoole.com/2012/09/11/ipc-to-scrutinise-futur......
>
> Okay, so there've been pages now written on how great the Paralympics
> were in #London2012. But to give praise where it is undoubtedly due,
> it was probably Beijing that first raised the bar and the status of
> the Paralympic games to, if not equal status, then a great deal closer
> to the Olympics than at any time before.
>
> . . .
>
> There was virtually no coverage of the Paralympics in the US. NBC who
> had both contracts (and who creamed a record 214 million viewers for
> the Olympics) virtually pulled out for the Paralympics.
>
>   "NBC did not show any live action and its 90-minute round-up
>    programme will not be broadcast until 16 September. Yet the
>    broadcaster said the total of five-and-a-half hours represented an
>    improvement on the 2008 Paralympics in Beijing, when viewers got a
>    single 90-minute highlights package."
>
> But the US media's no show has brought an interesting response from
> IPC President, Sir Philip Craven:
>
>   "We'll examine their values as they will examine ours. If the values
>    fit, we've got a chance. If they don't we'll go somewhere else.The
>    people of the USA, for example, particularly the parents and
>    families of the athletes, they are all ready for Paralympic sport.
>
>    Take the plunge, take the risk and then you'll succeed. [emphasis
>    added]"
>
> US sports journalist Jim Ferstle:
>
>   "It isn't a priority, they don't get the funding, they don't get the
>    attention and they aren't sold the same way the Olympics are,"
>
> It's a case of the rest of the world changing their view of
> disability, and the US falling behind. At a time when in London
> veterans from Iraq and Afghanistan featured prominently in the games
> but also in the opening and closing ceremony you have to wonder who in
> the States would take up the mantle so well worn by Channel 4 in the
> UK for Rio?
>
> Is there opportunity here for one of the smaller networks like Fox
> News, which like Channel 4 ordinarily does not `do' live sport, to
> begin redefining itself in the public imagination by taking on Phillip
> Craven's confident challenge for someone in the US to be bold and
> `take the risk' with Rio 2016?