0

So I have table items in my db. I want in Item.name replace - character which is at the end of the Item.name So I try to do it like this:

 items = Item.all
 items.each do |it|
 it.name=it.name.gsub('/\-$/','')
 it.save
 end

But it doesn't work. What do I do?

upd: I managed to do it like this:

i = Item.all
 i.each do |it|
 it.name=it.name.chomp('-')
 it.save
 end

But still don't get why first variant didn't work

name name
  • 37
  • 1
  • 5

4 Answers4

1

You can try sub! function of ruby.

Ex.

it.name.sub!("-","")

! represent as Bang method, so you not need store it again on item object.

Hardik Upadhyay
  • 2,639
  • 1
  • 19
  • 34
0

Try the below one it will definatly work for you.

items = Item.all
 items.each do |item|
 item.name = item.name.gsub('-','')
 it.save
 end
Bharat soni
  • 2,686
  • 18
  • 27
0

You should use like:

items = Item.all
 items.each do |it|
 if name.end_with? '-'
   it.name=it.name[0..-2]
 else
   it.name=it.name
 end
 it.save
 end

OR you should use this

 items = Item.all
 items.each do |it|
 it.name=it.name.chomp('-')  
 it.save
 end
Kaushlendra Tomar
  • 1,410
  • 10
  • 16
0

Have a look at this answer : Ruby, remove last N characters from a string?

so you just have to use the chomp method :

In your example :

items = Item.all
items.each do |it|
it.name=it.name.chomp
it.save
end
Community
  • 1
  • 1
Didi
  • 248
  • 2
  • 18