Skip to content

Instantly share code, notes, and snippets.

@landovsky
Last active March 19, 2018 14:07
Show Gist options
  • Save landovsky/6251fe994dd1536830ccddce52b161cd to your computer and use it in GitHub Desktop.
Save landovsky/6251fe994dd1536830ccddce52b161cd to your computer and use it in GitHub Desktop.
Why does Ruby modify frozen array?
a = [
{ entity: [1, 2], other: 1 },
{ entity: [2, 3], other: 3 }
]
def copy_examples_to_entities(array_of_examples)
array_of_examples.map do |example|
entities = example[:entity]
if entities.count > 1
entities.map do |entity|
example.tap { |ex| ex[:entity] = entity }
end
else
example
end
end.flatten
end
a.freeze
puts "Frozen? #{a.frozen?}"
copy_examples_to_entities(a)
puts "Frozen array == original array? #{a == [{ entity: [1, 2], other: 1 }, { entity: [2, 3], other: 3 }]}"
@Masa331
Copy link

Masa331 commented Mar 19, 2018

array = ['ahoj', 'baf']
array.freeze
# array << 'neco' # => RuntimeError: can't modify frozen Array
array.first.concat ' Tomasi'
# array # => ["ahoj Tomasi", "baf"]
arrray.first.freeze
array.first.concat(', freeznul jsi sice array, ale ne objekty v ni, ktere pokud nejsou frozen, tak jdou stale modifikovat') # => RuntimeError: can't modify frozen String

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment