Arrays, difference of operation

Hello,

I tried the following;
a = [3, 2, 1]
followed by;
a[3] = a[2] - 1
then, a contained [3, 2, 1, 0]

but, if I did the following;
b = “hello everybody”
followed by;
b[“body”] = “one”
then, b contained “hello everyone”

I can understand that a is an array holding numbers and when I do a[3]
it is performing an operation on element 4, while b is an array
holding characters and when I do a b[“body”] it seeks out the part of
that string containing “body” and does an operation on it.

So, to do an operation on 3 in array a, I tried doing a[“3”] = 4 which
gave an error as expected.

I’m a bit confused about this whole array thing, could someone please
elaborate on the above two different results for array operations?
Also, how would I seek an element in a numeric array without referring
to its index?

Best,

Mayuresh K. wrote:

I’m a bit confused about this whole array thing, could someone please
elaborate on the above two different results for array operations?
Also, how would I seek an element in a numeric array without referring
to its index?

Hello.

Your confussion comes from the fact that you assume that [] means an
array. In Ruby, [] means whatever you want. If a is an array, then
a[index] is an operation of reading the specified element, and
a[index]=value is the operation of writing the element. They can also be
written as a. and a.[]=(index,value), as [] and []= are just
method names.

As these are methods, they can be defined differently for other classes
than Array. For example, for String they are defined as “find the text
(and replace it with the value)”. If you define your class, you can even
do this:

class K
def
puts “#{a}:#{b}:#{c}”
end
end

K::new[2,:f,“asd”]

As you see, the result has nothing to do with arrays. It’s just a
method, the difference is only the fact that you can use the short
notation a[x] instead of a..

TPR.

Mayuresh K. wrote:

b = “hello everybody”
[…]
b is an array holding characters

No, it’s not. [“a”, “b”, “c”] is an array containing characters. “hello
everybody” is a string. String#[] has features that Array#[] does not.
Which
it can have for the very simple reason that those are two different
methods
in two entirely different classes.

Also, how would I seek an element in a numeric array without referring
to its index?

Array#find

HTH,
Sebastian