> It depends. Where do you get the data from? Is it a fixed set of
> values? etc.
ok, give me a try to explain. Lets take a look in the Hash
I would prefer to look at the input data and see the larger picture.
{"I OFF"=>["a8", "1e"], "E OFF"=>["98", "a0"], "E ON"=>["db"],
"I ON"=>["99"]}
The values "a8", "1e", "98" etc. are random generated values. There are
not fixed but they have an interval. Depending on the value if the LSB =
1 it is an ON and LSB = 0 it is a OFF. So normally we can say without
looking to the syntax
def value_?even(value)
return :E_ON if value & 0x01
return :E_OFF
end
Actually, to me it seems there are two values encoded in those Strings you
have above: one is either "I" or "E" and another one is "ON" or "OFF". For
me that means a much more appropriate way to store it would be an instance
with two attributes. You can easily have that with a Struct:
NameOfYourData = Struct.new :whatever_that_means, :enabled do
def self.from_string(s)
raise ArgumentError, "Invalid input: #{s}" unless
/\A(\w+)\s+(O(?:N|OFF))\z/ =~ s
new($1, $2 == "ON")
end
end
irb(main):007:0> x = NameOfYourData.from_string "E ON"
=> #<struct NameOfYourData whatever_that_means="E", enabled=true>
irb(main):008:0> x.enabled
=> true
irb(main):009:0> x.whatever_that_means
=> "E"
Of course you would pick more meaningful names.
But for a ruby newbie it is very difficult and confusing to understand
symbols in ruby. I have read so much articles and looked for example to
get it. But I think I need more time to understand symbols.
It's fairly easy when to use Symbols: you do that if the set of values is
restricted. In other programming languages you would often use an enum for
that (i.e. a type with a fixed set of values).
Now what do you suggest me, is it possible to implement this like I
explained?
As I said: without seeing the big picture and understanding what all this
is about and what those different strings represent it's not possible to
come up with good advice. We would need to know
- what the input data looks like
- what it means
- what you want to do with it
- what the whole purpose of the exercise is
Cheers
robert
···
On Fri, Jul 12, 2013 at 9:23 AM, stefan heinrich <lists@ruby-forum.com>wrote:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/