RubyLearning Blog

All about Ruby and Ruby on Rails

RubyLearning Blog header image 1

Convert bytes to megabytes

February 6th, 2007 · 3 Comments · Code Snippets, Ruby, Tricks

In one of my projects, I need to find the file-size in megabytes again and again. This simple method helps me to convert the size of a file in bytes to megabytes. This is useful for very large files.

MEGABYTE = 1024.0 * 1024.0
def bytesToMeg bytes
  bytes /  MEGABYTE
end

# big file
len = File.size("Dreamweaver8-en.exe")
puts len.to_s + ' bytes'  # displays 62651176 bytes
puts bytesToMeg(len).to_s + ' MB'  # displays 59.7488174438477 MB

One of the uses for PDF conversion is that by going through the process of converting PDF to Word you’ll have a more easily editable document than if you didn’t do PDF conversion and tried to edit a PDF file.

The program code is pretty obvious and as you can see the method uses division. However, it is best to wrap this functionality in a method.

Technorati Tags: ,

Posted by Satish Talim

Tags:

3 responses so far ↓

  • 1 zimbatm // Feb 6, 2007 at 3:02 pm

    Or use ruby-units :

    require ‘units’
    # big file
    len = File.size(”Dreamweaver8-en.exe”)
    puts len.to_unit(’B').to(’MB’) # same here

  • 2 satish // Feb 6, 2007 at 3:43 pm

    I guess you are talking about this?
    http://ruby-units.rubyforge.org/ruby-units/
    I did a gem install ruby-units, but the program that you mentioned did not work? Am I making a mistake somewhere?

  • 3 Satish Talim // Feb 14, 2007 at 2:59 pm

    The following worked -

    require ‘ruby-units’
    # big file
    len = File.size(”Dreamweaver8-en.exe”)
    puts len.to_unit(’B').to(’MB’)

Leave a Comment