Project

General

Profile

Actions

Bug #11803

closed

NoMethodError when calling String#gsub

Added by Anonymous over 8 years ago. Updated over 8 years ago.

Status:
Rejected
Target version:
-
ruby -v:
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]
[ruby-core:72043]

Description

Assigning the result of a call to String#gsub throws a NoMethodError. It seems to have to do with assigning the return value to a variable with the same name as the method returning the string gsub is called on. I've included short script which reproduces the issue.


Files

test_fail.rb (164 Bytes) test_fail.rb Anonymous, 12/11/2015 12:37 AM

Updated by Anonymous over 8 years ago

Updated by nobu (Nobuyoshi Nakada) over 8 years ago

  • Status changed from Open to Rejected
  def to_s
    return unless word
    word = word.gsub(/a/, "")

You make a new local variable here, and call gsub on it before assignment.

Updated by Hanmac (Hans Mackowiak) over 8 years ago

first i dont think its a good idea in a to_s method to change the value of the object.
otherwise you need to use @instance variables then it works:

class TestFail
  def initialize(word)
    @word = word
  end

  def to_s
    return unless @word
    @word.gsub(/a/, "")
  end

  def word
    @word
  end
end
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0