. View this ad or post your own Ruby Job!

Monday, October 31, 2005

Arrays in Ruby

What have I found out so far?
  • Definition of Ruby
  • Ruby Windows Installer
  • Interactive Ruby - Open a new DOS window and type irb --simple-prompt A prompt appears as >>
  • Run a Ruby program by typing ruby hello.rb
  • Learnt some features of Ruby like comments, naming rules, variables, constants, strings etc.
  • Various Text Editors/IDEs like SciTE, NotePad2
  • Constructs like the if else and while
  • Some methods in Ruby.

Today, I am going to look at arrays in Ruby. Arrays are best explained by the following example.
# Arrays
name = ['Satish', 'Talim', 'Ruby', 'Java']
puts name[0]
puts name[1]
puts name[2]
puts name[3]
# the next one outputs nil
puts name[4]
# we can add more elements too
name[4] = 'Pune'
puts name[4]
# we can add anything!
name[5] = 4.33
puts name[5]
# we can add an array to an array
name[6] = [1, 2, 3]
puts name[6]

# some methods on arrays
newarr = [45, 23, 1, 90]
puts newarr.sort
puts newarr.reverse
puts newarr.length

# iterator each - extracts each element into lang
languages = ['Pune', 'Mumbai', 'Bangalore']

languages.each do |lang|
puts 'I love ' + lang + '!'
puts 'Don\'t you?'
end


First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home

Valid XHTML 1.0!