Ruby on rails 创建一个在引用时返回字符串的ruby类

Ruby on rails 创建一个在引用时返回字符串的ruby类,ruby-on-rails,ruby,Ruby On Rails,Ruby,HTTParty的response对象在被引用时似乎返回#已解析的_response。例如: response = HTTParty.get(some_url) response # => { some: 'random', stuff: 'in here' } response.parsed_response # => { some: 'random', stuff: 'in here' } 此外,如果检查response类,它不是散列,而是响应对

HTTParty的response对象在被引用时似乎返回
#已解析的_response
。例如:

response = HTTParty.get(some_url)
response                 # => { some: 'random', stuff: 'in here' }
response.parsed_response # => { some: 'random', stuff: 'in here' }
此外,如果检查
response
类,它不是散列,而是响应对象

response.class # => HTTParty::Response
这很有用,因为您可以检查
response
上的其他内容,如
response.code
,也可以非常方便地引用响应以获得
解析的\u响应

我怎么能在自己的班级里做这样的事情?但是,在引用类时,我希望它返回一个字符串,而不是返回一个哈希。

下面是我想做的一个具体例子:

not_a_string = MyClass.new('hello', [1, 2, 3])
not_a_string        # => 'hello'
not_a_string.stuff  # => [1, 2, 3]
因此,在rspec中,测试应通过,如下所示:

not_a_string = MyClass.new('hello', [1, 2, 3])
not_a_string.should == 'hello'  # passes

这对你有用吗

class MyClass < String
  attr_reader :stuff

  def initialize(string, stuff)
    super string
    @stuff = stuff
  end
end
--编辑:改进的解决方案--

这更干净

class MyClass < Struct.new(:string, :stuff)
  def ==(other)
    string == other
  end

  def inspect
    string.inspect
  end
end

出于您的目的,只需定义
检查
==

class Test
  def initialize(string)
    @string = string.to_s
  end

  def inspect
    @string.inspect
  end

  def ==(other)
    @string == other
  end
end

t = Test.new 'asd' #=> "asd"
t #=> "asd"
t == 'asd' #=> true

是的,这是一个简洁的功能:) 您只需创建一个inspect方法;)下面是一个例子:

class Greeter
  def initialize(name)
    @name = name.capitalize
  end

  def salute
    puts "Hello #{@name}!"
  end

  def inspect
    "hey"
  end
end


g = Greeter.new 'world'
g  # hey

干杯

你想把{:a=>“b”}散列返回为“{:a=>“b”}”吗?你试过从
String
继承吗?哦,我想
inspect
解决方案更好,不过还是谢谢你!人力资源经理,你改进后的答案对我不适用。当我创建一个结构实例时,我得到了一个结构?我使用的是ruby-2.0.0-p0,可能是这样吗?啊,好的。我用的是1.9。也许这就是它的本来面目,尽管它很奇怪:它在ruby 1.9.3中为我工作,请看,我尝试过使用
to\s
做类似的事情。但是请注意,它返回的是
hey
,而不是
“hey”
。这是有区别的,因为
g==“hey”
将为false,这不是我想要的。你知道如何让
返回“嘿”
?这实际上是我比较喜欢的方式。
class Test
  def initialize(string)
    @string = string.to_s
  end

  def inspect
    @string.inspect
  end

  def ==(other)
    @string == other
  end
end

t = Test.new 'asd' #=> "asd"
t #=> "asd"
t == 'asd' #=> true
class Greeter
  def initialize(name)
    @name = name.capitalize
  end

  def salute
    puts "Hello #{@name}!"
  end

  def inspect
    "hey"
  end
end


g = Greeter.new 'world'
g  # hey