嘗試在Ruby中使用基礎...我已經佈置的代碼看起來很重複。還有更好的方法嗎?轉換十六進制,十進制,八進制和ASCII?
module Converter
def self.convert(value, from, to)
case from
when :hex
case to
when :dec
# code to change hex to dec
when :oct
# code to change hex to oct
when :bin
# code to change hex to bin
when :ascii
# code to change hex to ascii
end
when :dec
case to
when :hex
# code to change dec to hex
when :oct
# code to change dec to oct
when :bin
# code to change dec to bin
when :ascii
# code to change dec to ascii
end
when :oct
case to
when :hex
# code to change oct to hex
when :dec
# code to change oct to dec
when :bin
# code to change oct to bin
when :ascii
# code to change oct to ascii
end
when :bin
case to
when :hex
# code to change bin to hex
when :dec
# code to change bin to dec
when :oct
# code to change bin to oct
when :ascii
# code to change bin to ascii
end
when :ascii
case to
when :hex
# code to change ascii to hex
when :dec
# code to change ascii to dec
when :oct
# code to change ascii to oct
when :bin
# code to change ascii to bin
end
end
end
end
convert需要字符串和返回字符串,對吧?你能舉一些例子嗎?例如,十六進制是「0xXX」? – tokland 2011-04-24 20:54:11