user3114054
user3114054

Reputation:

Trying to convert strings to symbols

This creates an infinite loop and i'm blanking as to why this happens. When I don't use the push command, the loop doesn't happen.

#strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = [ "a", "b", "c" ]
symbols.each do |x| 
  symbols.push(x.to_sym)
end

Upvotes: 2

Views: 71

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

This is because, in each iteration with #each method you keep adding a new element to your original array symbols. Which causes an infinite loop. Rather do as below using Array#each_index:

code - I

symbols = [ "a", "b", "c" ]
symbols.each_index do |i|
  symbols[i]=symbols[i].to_sym
end
symbols # => [:a, :b, :c]

But the above code will update your original array. A slight modification in your code will do work as well :

code - II

symbols = [ "a", "b", "c" ]
nw_ary = symbols.each_with_object([]) do |e,a|
  a << e.to_sym
end
nw_ary # => [:a, :b, :c]

But you could also use symbols.map(&:to_sym) inplace of code -II and symbols.map!(&:to_sym) inplace of code -I. Read Array#map and Array#map! .

Upvotes: 2

falsetru
falsetru

Reputation: 369444

The following code appends items to symbols array (the same array), while iterate it; the block provides infinite items by appending to the array. (each use those items for iteration)

symbols.each do |x| symbols.push(x.to_sym) end
#^^^^^^             ^^^^^^^

Use Enumerable#map instead:

symbols.map { |x| x.to_sym }
# => [:a, :b, :c]
symbols.map &:to_sym
# => [:a, :b, :c]

or use another array instead of using the same array.

new_symbols = []
symbols.each do |x| new_symbols.push(x.to_sym) end
new_symbols
# => [:a, :b, :c]

Upvotes: 5

Related Questions