S
Steven Arnold
Forgive me if this is an elementary question and I am missing something =
obvious, but there is a behavior in Ruby that puzzles me a lot.
I don't see why the two blocks below do not produce the same output. =
One displays the numerically sorted array and the other does not.
# Block 1
myarray =3D ["210", "22"]
myarray =3D myarray.sort do |a,b|
a.to_i <=3D> b.to_i
end
puts myarray=20
# Block 2
myarray =3D ["210", "22"]
puts myarray.sort do |a,b|
a.to_i <=3D> b.to_i
end
In one case, I reassign myarray to the return value of the sort method =
for myarray and then print myarray. In the other case, I just directly =
print the return value of the sort method. Shouldn't the return value =
be the same in both cases, and therefore the output also the same?
Here is the same thing in the irb interface:
irb(main):001:0> myarray =3D ["210", "22"]
=3D> ["210", "22"]
irb(main):002:0> myarray =3D myarray.sort do |a,b|
irb(main):003:1* a.to_i <=3D> b.to_i
irb(main):004:1> end
=3D> ["22", "210"]
irb(main):005:0> puts myarray=20
22
210
=3D> nil
irb(main):006:0> myarray =3D ["210", "22"]
=3D> ["210", "22"]
irb(main):007:0> puts myarray.sort do |a,b|
irb(main):008:1* a.to_i <=3D> b.to_i
irb(main):009:1> end
210
22
=3D> nil
steven=
obvious, but there is a behavior in Ruby that puzzles me a lot.
I don't see why the two blocks below do not produce the same output. =
One displays the numerically sorted array and the other does not.
# Block 1
myarray =3D ["210", "22"]
myarray =3D myarray.sort do |a,b|
a.to_i <=3D> b.to_i
end
puts myarray=20
# Block 2
myarray =3D ["210", "22"]
puts myarray.sort do |a,b|
a.to_i <=3D> b.to_i
end
In one case, I reassign myarray to the return value of the sort method =
for myarray and then print myarray. In the other case, I just directly =
print the return value of the sort method. Shouldn't the return value =
be the same in both cases, and therefore the output also the same?
Here is the same thing in the irb interface:
irb(main):001:0> myarray =3D ["210", "22"]
=3D> ["210", "22"]
irb(main):002:0> myarray =3D myarray.sort do |a,b|
irb(main):003:1* a.to_i <=3D> b.to_i
irb(main):004:1> end
=3D> ["22", "210"]
irb(main):005:0> puts myarray=20
22
210
=3D> nil
irb(main):006:0> myarray =3D ["210", "22"]
=3D> ["210", "22"]
irb(main):007:0> puts myarray.sort do |a,b|
irb(main):008:1* a.to_i <=3D> b.to_i
irb(main):009:1> end
210
22
=3D> nil
steven=