# File lib/pathname.rb, line 311
  def realpath(*args)
    unless args.empty?
      warn "The argument for Pathname#realpath is obsoleted."
    end
    force_absolute = args.fetch(0, true)

    if %r{\A/} =~ @path
      top = '/'
      unresolved = @path.scan(%r{[^/]+})
    elsif force_absolute
      # Although POSIX getcwd returns a pathname which contains no symlink,
      # 4.4BSD-Lite2 derived getcwd may return the environment variable $PWD
      # which may contain a symlink.
      # So the return value of Dir.pwd should be examined.
      top = '/'
      unresolved = Dir.pwd.scan(%r{[^/]+}) + @path.scan(%r{[^/]+})
    else
      top = ''
      unresolved = @path.scan(%r{[^/]+})
    end
    resolved = []

    until unresolved.empty?
      case unresolved.last
      when '.'
        unresolved.pop
      when '..'
        resolved.unshift unresolved.pop
      else
        loop_check = {}
        while (stat = File.lstat(path = top + unresolved.join('/'))).symlink?
          symlink_id = "#{stat.dev}:#{stat.ino}"
          raise Errno::ELOOP.new(path) if loop_check[symlink_id]
          loop_check[symlink_id] = true
          if %r{\A/} =~ (link = File.readlink(path))
            top = '/'
            unresolved = link.scan(%r{[^/]+})
          else
            unresolved[-1,1] = link.scan(%r{[^/]+})
          end
        end
        next if (filename = unresolved.pop) == '.'
        if filename != '..' && resolved.first == '..'
          resolved.shift
        else
          resolved.unshift filename
        end
      end
    end

    if top == '/'
      resolved.shift while resolved[0] == '..'
    end
    
    if resolved.empty?
      Pathname.new(top.empty? ? '.' : '/')
    else
      Pathname.new(top + resolved.join('/'))
    end
  end