maxfry
maxfry

Reputation: 357

ruby modify object

I have code:

def crop_word (film_title)
  size = film_title.size
  film_title[0...size-2] if size > 4
end

film = "Electrocity"
p crop_word film

What must I do if I want to modify the object film? (How can I create crop_word method as a mutator method?)

p crop_word film #=> "Electroci"
p crop_word film #=> "Electro"
p crop_word film #=> "Elect"

Upvotes: 1

Views: 3990

Answers (4)

steenslag
steenslag

Reputation: 80085

def crop_word! (film_title)
  film_title.size > 4 ? film_title.slice!(0..-3) : film_title
end

puts crop_word! "1234567" #=>"12345"

Upvotes: 4

sawa
sawa

Reputation: 168209

The question is not clear. I suppose you want to remove the last character if it is longer than 4.

class String
    def crop_word!; replace(self[0..(length > 4 ? -2 : -1)]) end
end


puts 'Electrocity'.crop_word! # => 'Electrocit'

Upvotes: 0

Jonas Elfström
Jonas Elfström

Reputation: 31438

In Ruby you can't pass parameters by reference like in C-like languages. The easiest way is to return the new value and then assign in to the input variable.

film_title = crop_word(film_title)

What you can do is to place the film_title in a container.

class Film
  attr_accessor :title, :length
end

film = Film.new
film.title = "Butch Cassidy and the Sundance Kid"

def crop_word (film)
  length = film.title.length
  film.title=film.title[0..length-2] if length > 4
end

puts crop_word(film)
# Butch Cassidy and the Sundance K
puts crop_word(film)
# Butch Cassidy and the Sundance
puts crop_word(film)
# Butch Cassidy and the Sundan

I wouldn't recommend it but you could also monkey patch the String class

class String
  def crop_word!
    self.replace self[0..self.length-2] if self.length > 4
  end
end

title = "Fear and Loathing in Las Vegas"

title.crop_word!
# => "Fear and Loathing in Las Vega"
title.crop_word!
# => "Fear and Loathing in Las Veg"
title.crop_word!
# => "Fear and Loathing in Las Ve"

Finally there's the black magic of eval and binding which you probably would have to be insane to actually use.

def crop_word(s, bdg)
  eval "#{s}.chop!.chop! if #{s}.length > 4", bdg
end

title="The Dark Knight"
crop_word(:title, binding)
puts title
# The Dark Knig
crop_word(:title, binding)
puts title
# The Dark Kn
crop_word(:title, binding)
puts title
# The Dark

Also, your crop_word does not output what you seem to want since it keeps the trailing spaces.

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40553

def crop_word (film_title)
  size = film_title.size
  film_title[size-2..size]="" if size > 4
  film_title
end

In general you either have to use a method that already does an in-place mutation or reopen the relevant class and assign to self.

Upvotes: 0

Related Questions