English 中文(简体)
鲁比语和修饰语
原标题:Ruby and modifying self for a Float instance
  • 时间:2011-01-09 17:42:47
  •  标签:
  • ruby

我想改变浮标的自我价值。

我有以下方法:

class Float
  def round_by(precision)
    (self * 10 ** precision).round.to_f / 10 ** precision
  end
end

我也想加上这一轮_! 改变自我价值的方法。

class Float
  def round_by!(precision)
    self = self.round_by(precision)
  end
end

但我要说的是,我可以改变自我价值。

任何想法?

最佳回答

您可更改<代码>本身的价值。 它总是提到目前的目标,你可以指出其他目标。

当你想要改变物体的价值时,你要么通过采用其他突变方法,要么制定或改变案例的数值,而不是试图重新编排<代码>本身<>。 然而,在这种情况下,由于<代码>Float没有经过任何改动的方法,而设定模型变量就没有购买任何东西,因为任何情况下的变量都不会影响任何违约的浮动作业。

因此,底线是:你可以在浮标上写出变数方法,至少不是你想要的。

问题回答

你们还可以创造一个等级,并在一个实例变量中储存浮体:

class Variable

  def initialize value = nil
    @value = value
  end

  attr_accessor :value

  def method_missing *args, &blk
    @value.send(*args, &blk)
  end

  def to_s
    @value.to_s
  end

  def round_by(precision)
    (@value * 10 ** precision).round.to_f / 10 ** precision
  end

  def round_by!(precision)
    @value = round_by precision
  end
end

a = Variable.new 3.141592653

puts a           #=> 3.141592653

a.round_by! 4

puts a           #=> 3.1416

http://rubychallenger.blogspot.com/201103/class-variable-to-increment-fixnum.html” rel=“nofollow” 。

这实际上是一个很好的问题,我很抱歉说,你可以说——至少不使用<代码>。 Float。 它不可改变。 我的建议是,像在伪装编码中那样,创建你自己的班子(由卡继承所有方法)。

class MyFloat < Float
  static CURRENT_FLOAT

  def do_something
    CURRENT_FLOAT = (a new float with modifications)
  end
end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签