Reputation: 13
I don't understand why this isn't working. I've only been programming in ruby for a few months now but I feel like I at least know the basics, and this seems to me like it is basic. Why wont this each
iterator capitalize each element in the array? I feel like this should work, it feels like a no brainer. I feel like I have done things like this a million times before and they worked as intended, but for some reason this will not work? Is it something I am misunderstanding about how arrays work? I felt like that was the case, but when I do puts array[0].capitalize it capitalizes the element as intended. Why wont the each
iterator do the same? This is absolutely driving me nuts and is basically standing in the way of a larger project where I do something similar.
array = []
array << "apple"
array << "banana"
array << "peach"
array.each do |x|
x.capitalize
end
puts array #returns all non-capitalized words
puts array[0].capitalize #returns Apple...wtf why doesn't for loop work then?!?
puts "apple".capitalize #returns Apple as expected
Upvotes: 0
Views: 103
Reputation: 2303
The best thing you can do is to go to irb
in your terminal and simple put a puts
inside your loop to see what is actually going on. There, you can see that each time the output is capitalized and that's correct, but the each
method does nothing to the array. It just iterates for each element. That's the reason that the final output is non-capitalized elements.
array = []
array << "apple"
array << "banana"
array << "peach"
array.each do |x|
puts x.capitalize
end
Printed values in irb:
Apple
Banana
Peach
but the actual returned value is this => ["apple", "banana", "peach"]
Upvotes: -1
Reputation: 504
I just did a quick test in irb and array.map will create a new array with the idividuals capitalized. array.each will iterate through and do whatever you want to copies of the values in the array, but not change the array. If you wanted to change the array I would try
array = array.map do |x|
x.capitalize
end
Upvotes: 0
Reputation: 13921
And here is a slightly more advance ruby way of doing it:
array.map! &:capitalize
Upvotes: 0
Reputation: 7349
The problem is the method you're calling. capitalize
makes no modification to the string, but rather returns a new string. You want to call capitalize!
:
x = "apple"
puts x.capitalize # "Apple"
puts x # "apple"
x.capitalize!
puts x # "Apple"
Another option would be to create a new array using collect
like so:
array = ["apple"]
new_array = array.collect do |x|
x.capitalize
end
puts array # ["apple"]
puts new_array # ["Apple"]
Upvotes: 4
Reputation: 44725
capitalize
creates anew string and do not modify starting string. Use capitalize!
instead capitalize
or map!
instead of each
.
Upvotes: 0
Reputation: 11385
When you do
x.capitalize
it returns a copy of the string. To do what you want, you should change that line to
x.capitalize!
which will modify the existing element, instead of returning a copy.
Upvotes: 0