为什么两个正整数在分割时等于零?

时间:2013-07-23 14:12:51

标签: ruby-on-rails ruby function integer

我在我的模型中创建了一个函数,用于确定图像的尺寸和偏移量,当使用carrierwave缩放到一定大小时:

def get_auto_crop_dims(original_width, original_height, cropped_width, cropped_height)
  auto_dims = {:scale_width => 0, :scale_height => 0, :offset_x => 0, :offset_y => 0}

  # IF original image is the SAME orientation as container ie. portrait vs. portrait THEN image largest dimension = 100%
  # IF original image is the DIFFERENT orientation as container ie. portrait vs. landscape THEN image smallest dimension = 100%

  if ((cropped_height >= cropped_width and original_height >= original_width) or (cropped_height >= cropped_width and original_height <= original_width))
    # height 100%
    auto_dims[:scale_height] = cropped_height
    auto_dims[:scale_width] = (auto_dims[:scale_height]/original_height)*original_width
    auto_dims[:offset_y] = 0
    auto_dims[:offset_x] = (auto_dims[:scale_width]-cropped_width)/2
  else 
    # width 100%
    auto_dims[:scale_width] = cropped_width
    auto_dims[:scale_height] = (auto_dims[:scale_width]/original_width)*original_height
    auto_dims[:offset_x] = 0
    auto_dims[:offset_y] = (auto_dims[:scale_height]-cropped_height)/2
  end

  return auto_dims

end 

通过以下方式调用:

dims[:title][:width], dims[:title][:height] = `identify -format "%wx%h" #{image.title.file.path}`.split(/x/)
    dims[:title].merge!(get_auto_crop_dims(dims[:original][:width].to_i, dims[:original][:height].to_i, dims[:title][:width].to_i, dims[:title][:height].to_i))

self.dimensions = dims.to_json

上传图片后返回的结果为:

> PageImage.last.dimensions
  PageImage Load (0.8ms)  SELECT `page_images`.* FROM `page_images` ORDER BY `page_images`.`id` DESC LIMIT 1
 => "{\"original\":{\"width\":\"1600\",\"height\":\"1200\\n\"},\"title\":{\"width\":\"960\",\"height\":\"384\\n\",\"scale_width\":960,\"scale_height\":0,\"offset_x\":0,\"offset_y\":-192},\"thumb\":{\"width\":\"220\",\"height\":\"130\\n\",\"scale_width\":220,\"scale_height\":0,\"offset_x\":0,\"offset_y\":-65}" 

问题是:

dims[:title][:scale_width] = 0 

意味着存在某种问题:

auto_dims[:scale_height] = (auto_dims[:scale_width]/original_width)*original_height 

我无法理解为:

:scale_width = 960 & original_width = 1600 & original_height = 1200 

为什么不dims[:title][:scale_width] = 720?。

1 个答案:

答案 0 :(得分:3)

当你在Ruby中划分整数时,它们也不会像你期望的那样分成小数。例如:

  • 9 / 4 = 2
  • 4 / 9 = 0

您在4 / 9中看到的是当您将比例宽度除以原始宽度时发生的情况,这是一个更大的数字。要获得您希望的小数,其中一个操作数必须是浮点数(例如4.0 / 9 = 0.444 ...)。因此,您可以将代码更改为:

auto_dims[:scale_height] = (auto_dims[:scale_width].to_f/original_width)*original_height

to_f调用只是将其中一个操作数更改为浮点数。