Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby Dir.entries doesn't recognize special characters

I'm using

Dir.entries("myFolder")

to get all the filenames. The problem is that instead of some special characters I get placeholders for them. The error occurs if filenames contain special characters like Č, Š and so on.

I've specified the file encoding:

#encoding: utf-8.

On linux this worked, on Windows it doesn't.

Result from the test in irb:

[".", "..", "MA\xC8KA.png", "PES.png", "VLAK.png", "\x8EOGA.png"]

It should be:

[".", "..", "MAČKA.png", "PES.png", "VLAK.png", "ŽOGA.png"]

Is there any other way of fixing this other than substituting these characters if there are any?

--------EDIT-----------

irb(main):001:0> Dir.entries("myFolder").map {|e| e.force_encoding('Windows-1250').encode('UTF-8')}

=> [".", "..", "MA\u010CKA.png", "PES.png", "VLAK.png", "\u017DOGA.png"]

irb(main):002:0> Dir.entries("myFolder").map {|e| e.force_encoding('UTF-8')}

=> [".", "..", "MA\xC8KA.png", "PES.png", "VLAK.png", "\x8EOGA.png"]

--------EDIT-----------

---------EDIT 2-------------

#encoding: utf-8
require 'green_shoes'

Shoes.app do

  button "Get sample image name" do
    @words_images = Dir.entries("myFolder").each {|word| word.gsub!(".png", "")}
    @words_images.delete(".")
    @words_images.delete("..")
    @test.append{para @words_images.sample}
  end

  @test = stack do
  end

end

---------EDIT 2-------------

Thank you.

Regards, Seba

like image 831
Sebastjan Hribar Avatar asked Sep 02 '25 17:09

Sebastjan Hribar


1 Answers

I solved the issue by passing the encoding option when reading the files in the directory:

Dir.entries("myFolder", encoding: "utf-8")

Any attempt later on to change or force change the encoding failed.

A reminder to myself to read the docu more carefully...

regards, seba

like image 173
Sebastjan Hribar Avatar answered Sep 04 '25 06:09

Sebastjan Hribar