Skip to content

Instantly share code, notes, and snippets.

@andyjeffries
Last active March 10, 2022 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyjeffries/a534ef6d50ad145a902d439906958d38 to your computer and use it in GitHub Desktop.
Save andyjeffries/a534ef6d50ad145a902d439906958d38 to your computer and use it in GitHub Desktop.
objects = [MyObject.new(name: "John Smith"), MyObject.new(name: "Joan Smith"), MyObject.new(name: "Jane Doe")]
objects.select {|o| o.name["Smith"]}.each do |o|
o.name.gsub!("Smith", "Jones")
o.save
end
@andyjeffries
Copy link
Author

The gsub! is important, without the ! the gsub will return a new string, rather than change it in place. So these are equivalent:

o.name.gsub!("Smith", "Jones")
o.name = o.name.gsub("Smith", "Jones")

@andyjeffries
Copy link
Author

Also, I'm assuming you're not using ActiveRecord... If you are then you'd do something like this:

MyObject.where("name like ?", "%Smith%").each do |o|
  #  ...
end

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