Brian Candler wrote:
> Anthony Ob wrote:
>> puts name = 'Prune'
> 
> That assigns 'Prune' to name (so name is no longer pointing to an Array, 
> it's pointing to a String), then prints the value. It's the same as:
> 
>   name = 'Prune'
>   puts name
> 
> Maybe meant:
> 
>   name[4] = 'prune'
> 
> or perhaps
> 
>   puts name == 'Prune'
> 
> (which would have shown 'false' without changing the array)
> 
>> puts name[4]
> 
> Given that name is a String at this point, that prints character number 
> 4 (the 5th character). This will print the byte code 101 in Ruby 1.8, 
> and the string "e" in ruby 1.9
> 
>> # We can add anything!
>> name[5] = 4.33
> 
> But you can't set the nth character of a string to be a floating point 
> value.






Updated code, got rid of the e:




# p018arrays.rb
# Arrays

# Empty array
var1 = []
# Array index starts from 0
puts var1[0]

# An array holdling a single number
var2 = [5]
puts var2[0]

# An array holding two strings
var3 = ['Hello', 'Goodbye']
puts var3[0]
puts var3[1]

flavour = 'mango'
# An array whose elements are pointing
# To three objects - a float, a string and an array
var4 = [80.5, flavour, [true, false]]
puts var4[2]

# A trailing comma is ignored
name = ['Satish', 'Talim', 'Ruby', 'Java']
puts name[0]
puts name[1]
puts name[2]
puts name[3]
# The next one outputs nil
# nil is Ruby's way of saying nothing
puts name[4]
# We can add anything!
name = '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.length
puts newarr.first
puts newarr.last

=begin
Method each (iterator) - extracts each element into lang
do end is a block of code
we shall talk about blocks soon,
variable lang refers to each item in the array as it goes through the 
loop
=end
languages = ['Pune', 'Mumbai', 'Bangalore']
languages.each do |lang|
  puts 'I love ' + lang + '!'
  puts 'Don\'t you?'
end

# delete an entry in the middle and shift the remaining entries
languages.delete('Mumbai')
languages.each do |lang|
  puts 'I love ' + lang + '!'
  puts 'Don\'t you?'
end


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