Module: HumanReadable
- Defined in:
- lib/human_readable.rb
Overview
Copyright © 2009 Matteo Sasso
This file is part of durb.
durb is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
durb is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with durb. If not, see <www.gnu.org/licenses/>.
Constant Summary collapse
- SUFFIXES =
[' ', 'k', 'm', 'g', 't', 'p']
Instance Method Summary collapse
Instance Method Details
#size_to_text(size) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/human_readable.rb', line 29 def size_to_text(size) exp = 0 return size.to_s if size < 10000 while size > 999 size /= 1024.0 exp += 1 end if size < 10 "%.1f%s" % [size, SUFFIXES[exp]] else "%d%s" % [size.round, SUFFIXES[exp]] end end |
#text_to_size(text) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/human_readable.rb', line 21 def text_to_size(text) number, multiplier = text.match(/^(\d+)(\D)?$/)[1..-1] exp = multiplier ? SUFFIXES.index(multiplier) : 0 raise ArgumentError, "Unknown suffix: %s" % multiplier if not exp return number.to_i * 1024**exp end |