About Ruby Error Codes

Asked 1 years ago, Updated 1 years ago, 404 views

I have a question about ruby error code.
I'm studying with a book called Ruby Introduction 2nd Edition.
This document uses ruby 1.9.3 and I use ruby 3.0.5.
When I created a library management application in this book and entered Japanese at the command prompt when registering the library data, an error code appeared, so I would appreciate it if you can you tell me the solution?(If you type everything in half-width, there will be no error.)

#encoding:utf-8
require 'rubygems' # Described when installed with RubyGems
require 'dbi'# Use DBI
require 'date'

classBookInfo
    # Initialize an instance of the BookInfo
    default initialize(title, author, page, publish_date)
        @title=title
        @author=author
        @page=page
        @publish_date=publish_date
    end

    # Provides accessories for attributes to be considered first
    attr_accessor:title, :author, :page, :publish_date

    # Returns a string representation of an instance of the BookInfo class
    def to_s
        "#{@title}, #{@author}, #{@page}, #{@publish_date}"
    end

    # add an operation to format and output library data
    # You can specify an item separator as an argument
    # If the argument is omitted, a new line is a delimiter.
    def toFormattedString(sep="\n")
        "Book Name: #{@title}#{sep}Author Name: #{@author}#{sep}Number of pages: #{@page}Page#{sep}Date of publication: #{@publish_date}#{sep}"
    end
end

# Define the BookInfoManager class
classBookInfoManager
    def initialize(sqlite_name)
        # Connect to SQLite database file
        @db_name = sqlite_name
        @dbh = DBI.connect("DBI:SQLite3:#{@db_name}")
    end

    # initialize a library database
    defaultBookInfos
        puts "\n0.Initialize library database"
        print "Do you want to initialize?(If it's Y/y, I'll delete it): "
        # capitalize the characters read
        yesno=gets.chomp.upcase
        if/^Y$/=~yesno
            # Initialize only when Y is a single character

            # If there is already a table "bookinfos" in this database, delete it.
            @bh.do("drop table if exists bookinfos")
            # Create a new "bookinfos" table
            @d bh.do("create table bookinfos(
                id varchar(50) not null,
                title varchar(100) not null,
                author varchar(100) not null,
                page int not null,
                publish_date datetime not null,
                primary key (id)
            );")
            puts"\nDatabase initialized."
            
        end
    end

    # register one's library data
    defaultBookInfo
        puts "\n1. Registering library data"
        print "Register the library data."

        # create an instance of one collection of data
        book_info=BookInfo.new("", "", 0, Date.new)
        # Enter the data to be registered for each item
        print "\n"
        print "Key:"
        key=gets.chomp
        print "Book Name:"
        book_info.title=gets.chomp
        print "Author Name:"
        book_info.author=gets.chomp
        print " Page: "
        book_info.page=gets.chomp.to_i
        print "Year of publication:"
        year=gets.chomp.to_i
        print "Month of publication:"
        month=gets.chomp.to_i
        print "Date of publication:"
        day=gets.chomp.to_i
        book_info.publish_date=Date.new(year, month, day)

        # register one created collection of data in a database
        @d bh.do("insert into bookinfos values(
            \'#{key}\',
            \'#{book_info.title}\',
            \'#{book_info.author}\',
            \'#{book_info.page}\',
            \'#{book_info.publish_date}\"
        );")

        puts"\nRegistered successfully."
    end

    # display a list of collection data
    deflistAllBookInfos
        # hash table that changes the item name on the table to Japanese
        item_name={'id'=>"key", 'title'=>"book name", 'author'=>"author name", 'page'=>"page count", 'public_date'=>"date of publication"}

        puts "\n2.Viewing Library Data"
        print "View the library data."

        puts"\n-------------------"

        # read and display data from a table
        [email protected]("select*frombookinfos")

        # Take the results of the select statement one row at a time and repeat them
        counts = 0
        sth.each do | row |
            #row has one piece of data.
            # Use the each_with_name method to extract and display values and item names
            row.each_with_name do | val, name |
                # Display item names as Japanese item names
                puts"#{item_name[name]}:#{val.to_s}"
            end
            puts "-----------------"
            counts + = 1
        end

        # release the results of
        sth.finish

        "\n#{counts} displayed"
    end

    # Repeat process selection and post-selection processing
    def run
        while true
            # Display the function selection screen
            print"
            0. Initializing the library database
            1. Registration of collection data
            2. Display of collection data
            9. Closing
            Please select a number (0,1,2,9): "

            # wait for characters to be entered
            num=gets.chomp
            case
            when "0" == num
                # initialization of library database
                initBookInfos
            when "1" == num
                # Registration of collection data
                addBookInfo
            when"2" == num
                # Display of collection data
                listAllBookInfos
            when "9" == num
                # Terminate connection to database
                @dbh.disconnect
                # Application Termination
                puts "\nExit"
                break;
            else
                # Return to processing wait selection screen
            end
        end
    end
end

# This is where the application runs.
# Specify SQLite3 database for collection data
book_info_manager = BookInfoManager.new("bookinfo_sqlite.db")

# Repeat BookInfoManager process selection and post-selection processing
book_info_manager.run

When registering the collection data, if there is Japanese in the book name or author name, the following error will appear.(If the command prompt character code is set to utf-8 setting, the command prompt will be terminated as soon as you type in Japanese.)

C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/dbi-0.4.5/lib/dbi/handles/database.rb:238:in`=~':invalid byte sequence in UTF-8 (ArgumentError)
        from C: /Ruby30-x64/lib/ruby/gems/3.0.0/gems/dbi-0.4.5/lib/dbi/handles/database.rb:238:in`!~'
        from C: /Ruby30-x64/lib/ruby/gems/3.0.0/gems/dbi-0.4.5/lib/dbi/handles/database.rb:238:in`check_statement'
        from C: /Ruby30-x64/lib/ruby/gems/3.0.0/gems/dbi-0.4.5/lib/dbi/handles/database.rb:233:in `sanity_check'
        from C: /Ruby30-x64/lib/ruby/gems/3.0.0/gems/dbi-0.4.5/lib/dbi/handles/database.rb: 103:in `do'
        from ex2201.rb:90:in `addBookInfo'
        from ex2201.rb:152:in `run'
        from ex2201.rb:174:in `<main>'

I am a beginner in ruby and programming, so I would appreciate it if you could provide me with as specific a solution as possible.

ruby command-prompt

2023-02-11 12:37

1 Answers

It appears to be a bug (details later) that may occur in conjunction with a new console (including Windows Terminal) implemented in Windows 10 and later.It has been fixed in 3.2.0 and above, so try raising Ruby version to 3.2.0 and above.

Also, since this is a problem specific to the new console in Windows, it can be avoided by using WSL, legacy consoles, etc. (this will also be discussed later).

Previously, new consoles and WindowsTerminals implemented from Windows 10 had reported garbled characters when using the Windows version of Ruby at command prompts.You said you weren't sure for a while, but now you know the cause and the solution.

Bug#18588: ruby-e'p gets' with Japanese characters gets additional invalid leading chars and caught Encoding::InvalidByteSequenceError-Ruby master-Ruby Issue Tracking System

The reason is that the new console itself has a bug that passes strange data for multi-byte characters in ANSI version of PeekConsoleInput, and Ruby received the wrong byte string from the beginning, resulting in errors such as incorrect character codes.Starting with 3.2.0, a commit to correct the above (using PeekConsoleInputW for UNIXODE) has been adopted.

これ This did not happen on consoles such as Windows 7.This issue is specific to the new console after Windows 10.Also, ASCII only passed the correct character code, so there was no problem.

Raise Ruby version to 3.2.0 or higher.
If you're not particular about the version, I think it's easiest to update it.

Use legacy console mode.
The legacy console (legacy console) is not gone and can be switched.Please refer to the following for details.
Legacy Console Mode – Windows Desktop - Windows Console | Microsoft Learn

Use WSL.
Ruby's main operating environment is Linux, and Linux's environment, including the library, is the most tested and most run.Therefore, Linux is the most stable (less bugs).Starting with Windows 10, you can easily build a Linux environment using WSL.Therefore, it is safer to use WSL for Ruby development.See below for instructions on how to chair a WSL.
Install WSL|Microsoft Learn

Use a non-Windows environment.
You can avoid this problem by abandoning Windows to a Mac, Linux, or other operating system.


2023-02-11 12:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.