How to use code block in Ruby? -


i have following code

animals=['lion','tiger','zebra'] animals.each{|a| puts a} 

i wanted print tiger in array wrote this

animals.each{|a| if a==1 puts animals[a]} 

but it's not working why?

the wrong did in case:-

animals.each{|a| if animals[a]==2 puts a} 
  • inline if statement put in wrong way.

  • #each passes element of array,not index. animals[a] not work. throw error no implicit conversion of string integer (typeerror).

do below using array#each_index

animals=['lion','tiger','zebra'] animals.each_index{|a| puts animals[a] if animals[a] == 'tiger' } # >> tiger 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -