How can I add a key-value pair to a hash without name?











up vote
0
down vote

favorite












This is my ruby file with hash:




book.rb




class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status



def initialize(title, author, language, classification, isbn, book_id, borrow_status)
@title = title
@author = author
@language = language
@classification = classification
@isbn = isbn
@book_id = book_id
@borrow_status = borrow_status
end

def bookid
@book_id
end

def booklist
@title = @title.split(/ |_|-/).map(&:capitalize).join(" ")
@author = @author.split(/ |_|-/).map(&:capitalize).join(" ")
@language = @language.capitalize
@isbn.to_s
@book_id.to_s

{
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}
end


end


for now, I already have five key-value pair for this hash, they are in ruby file named top.rb:



$books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
$books2 = Book.new("ninteen eighty four","george orwell","english","literature",9781374677817, 2,"available")
$books3 = Book.new("japanese in 30 days","naomi ono","japanese","education",9787928365729,3,"available")
$books4 = Book.new("brand famous: how to get everyone talking about your business","linzi boyd","english","business",9780857084903,4,"borrowed")
$books5 = Book.new("SQL in 10 mins","ming zhong, xiaoxia liu","chinese","hi tech",9787115313980,5,"unavailable")


and using the method below to output the result:



    def status
bookstatus = gets.chomp.to_s
if bookstatus == "status"
puts "Status:" + "n" + "#{$books1.booklist[:Book_ID]}: #{$books1.booklist[:Title]}: #{$books1.booklist[:Status]}"
puts "#{$books2.booklist[:Book_ID]}:#{$books2.booklist[:Title]}: #{$books2.booklist[:Status]}"
puts "#{$books3.booklist[:Book_ID]}:#{$books3.booklist[:Title]}: #{$books3.booklist[:Status]}"
puts "#{$books4.booklist[:Book_ID]}:#{$books4.booklist[:Title]}: #{$books4.booklist[:Status]}"
puts "#{$books5.booklist[:Book_ID]}:#{$books5.booklist[:Title]}: #{$books5.booklist[:Status]}"
else
puts "error"
end
end


For now, I am going to add some more value, I am going to let user enter the information of books (e.g., title = gets.chomp.to_s), and make a new key-value pair for the book added.



As I know, add new key-value pair to ruby is like below:



my_hash = {:a => 5}
my_hash[:key] = "value"


But, the hash in book.rb does not have any name, I tried to give it a name like



book_list = {
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}


it will output error.



My question is, I would like to know how can I add a new key-value pair to the hash in my ruby file, which has no name?



Thanks.










share|improve this question






















  • The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
    – Cary Swoveland
    Nov 8 at 21:03










  • You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
    – Cary Swoveland
    Nov 8 at 21:04

















up vote
0
down vote

favorite












This is my ruby file with hash:




book.rb




class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status



def initialize(title, author, language, classification, isbn, book_id, borrow_status)
@title = title
@author = author
@language = language
@classification = classification
@isbn = isbn
@book_id = book_id
@borrow_status = borrow_status
end

def bookid
@book_id
end

def booklist
@title = @title.split(/ |_|-/).map(&:capitalize).join(" ")
@author = @author.split(/ |_|-/).map(&:capitalize).join(" ")
@language = @language.capitalize
@isbn.to_s
@book_id.to_s

{
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}
end


end


for now, I already have five key-value pair for this hash, they are in ruby file named top.rb:



$books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
$books2 = Book.new("ninteen eighty four","george orwell","english","literature",9781374677817, 2,"available")
$books3 = Book.new("japanese in 30 days","naomi ono","japanese","education",9787928365729,3,"available")
$books4 = Book.new("brand famous: how to get everyone talking about your business","linzi boyd","english","business",9780857084903,4,"borrowed")
$books5 = Book.new("SQL in 10 mins","ming zhong, xiaoxia liu","chinese","hi tech",9787115313980,5,"unavailable")


and using the method below to output the result:



    def status
bookstatus = gets.chomp.to_s
if bookstatus == "status"
puts "Status:" + "n" + "#{$books1.booklist[:Book_ID]}: #{$books1.booklist[:Title]}: #{$books1.booklist[:Status]}"
puts "#{$books2.booklist[:Book_ID]}:#{$books2.booklist[:Title]}: #{$books2.booklist[:Status]}"
puts "#{$books3.booklist[:Book_ID]}:#{$books3.booklist[:Title]}: #{$books3.booklist[:Status]}"
puts "#{$books4.booklist[:Book_ID]}:#{$books4.booklist[:Title]}: #{$books4.booklist[:Status]}"
puts "#{$books5.booklist[:Book_ID]}:#{$books5.booklist[:Title]}: #{$books5.booklist[:Status]}"
else
puts "error"
end
end


For now, I am going to add some more value, I am going to let user enter the information of books (e.g., title = gets.chomp.to_s), and make a new key-value pair for the book added.



As I know, add new key-value pair to ruby is like below:



my_hash = {:a => 5}
my_hash[:key] = "value"


But, the hash in book.rb does not have any name, I tried to give it a name like



book_list = {
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}


it will output error.



My question is, I would like to know how can I add a new key-value pair to the hash in my ruby file, which has no name?



Thanks.










share|improve this question






















  • The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
    – Cary Swoveland
    Nov 8 at 21:03










  • You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
    – Cary Swoveland
    Nov 8 at 21:04















up vote
0
down vote

favorite









up vote
0
down vote

favorite











This is my ruby file with hash:




book.rb




class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status



def initialize(title, author, language, classification, isbn, book_id, borrow_status)
@title = title
@author = author
@language = language
@classification = classification
@isbn = isbn
@book_id = book_id
@borrow_status = borrow_status
end

def bookid
@book_id
end

def booklist
@title = @title.split(/ |_|-/).map(&:capitalize).join(" ")
@author = @author.split(/ |_|-/).map(&:capitalize).join(" ")
@language = @language.capitalize
@isbn.to_s
@book_id.to_s

{
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}
end


end


for now, I already have five key-value pair for this hash, they are in ruby file named top.rb:



$books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
$books2 = Book.new("ninteen eighty four","george orwell","english","literature",9781374677817, 2,"available")
$books3 = Book.new("japanese in 30 days","naomi ono","japanese","education",9787928365729,3,"available")
$books4 = Book.new("brand famous: how to get everyone talking about your business","linzi boyd","english","business",9780857084903,4,"borrowed")
$books5 = Book.new("SQL in 10 mins","ming zhong, xiaoxia liu","chinese","hi tech",9787115313980,5,"unavailable")


and using the method below to output the result:



    def status
bookstatus = gets.chomp.to_s
if bookstatus == "status"
puts "Status:" + "n" + "#{$books1.booklist[:Book_ID]}: #{$books1.booklist[:Title]}: #{$books1.booklist[:Status]}"
puts "#{$books2.booklist[:Book_ID]}:#{$books2.booklist[:Title]}: #{$books2.booklist[:Status]}"
puts "#{$books3.booklist[:Book_ID]}:#{$books3.booklist[:Title]}: #{$books3.booklist[:Status]}"
puts "#{$books4.booklist[:Book_ID]}:#{$books4.booklist[:Title]}: #{$books4.booklist[:Status]}"
puts "#{$books5.booklist[:Book_ID]}:#{$books5.booklist[:Title]}: #{$books5.booklist[:Status]}"
else
puts "error"
end
end


For now, I am going to add some more value, I am going to let user enter the information of books (e.g., title = gets.chomp.to_s), and make a new key-value pair for the book added.



As I know, add new key-value pair to ruby is like below:



my_hash = {:a => 5}
my_hash[:key] = "value"


But, the hash in book.rb does not have any name, I tried to give it a name like



book_list = {
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}


it will output error.



My question is, I would like to know how can I add a new key-value pair to the hash in my ruby file, which has no name?



Thanks.










share|improve this question













This is my ruby file with hash:




book.rb




class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status



def initialize(title, author, language, classification, isbn, book_id, borrow_status)
@title = title
@author = author
@language = language
@classification = classification
@isbn = isbn
@book_id = book_id
@borrow_status = borrow_status
end

def bookid
@book_id
end

def booklist
@title = @title.split(/ |_|-/).map(&:capitalize).join(" ")
@author = @author.split(/ |_|-/).map(&:capitalize).join(" ")
@language = @language.capitalize
@isbn.to_s
@book_id.to_s

{
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}
end


end


for now, I already have five key-value pair for this hash, they are in ruby file named top.rb:



$books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
$books2 = Book.new("ninteen eighty four","george orwell","english","literature",9781374677817, 2,"available")
$books3 = Book.new("japanese in 30 days","naomi ono","japanese","education",9787928365729,3,"available")
$books4 = Book.new("brand famous: how to get everyone talking about your business","linzi boyd","english","business",9780857084903,4,"borrowed")
$books5 = Book.new("SQL in 10 mins","ming zhong, xiaoxia liu","chinese","hi tech",9787115313980,5,"unavailable")


and using the method below to output the result:



    def status
bookstatus = gets.chomp.to_s
if bookstatus == "status"
puts "Status:" + "n" + "#{$books1.booklist[:Book_ID]}: #{$books1.booklist[:Title]}: #{$books1.booklist[:Status]}"
puts "#{$books2.booklist[:Book_ID]}:#{$books2.booklist[:Title]}: #{$books2.booklist[:Status]}"
puts "#{$books3.booklist[:Book_ID]}:#{$books3.booklist[:Title]}: #{$books3.booklist[:Status]}"
puts "#{$books4.booklist[:Book_ID]}:#{$books4.booklist[:Title]}: #{$books4.booklist[:Status]}"
puts "#{$books5.booklist[:Book_ID]}:#{$books5.booklist[:Title]}: #{$books5.booklist[:Status]}"
else
puts "error"
end
end


For now, I am going to add some more value, I am going to let user enter the information of books (e.g., title = gets.chomp.to_s), and make a new key-value pair for the book added.



As I know, add new key-value pair to ruby is like below:



my_hash = {:a => 5}
my_hash[:key] = "value"


But, the hash in book.rb does not have any name, I tried to give it a name like



book_list = {
:Title => @title,
:Author => @author,
:Language => @language,
:Classification => @classification,
:ISBN => @isbn,
:Book_ID => @book_id,
:Status => @borrow_status,
}


it will output error.



My question is, I would like to know how can I add a new key-value pair to the hash in my ruby file, which has no name?



Thanks.







ruby






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 8 at 17:52









Runkang

84




84












  • The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
    – Cary Swoveland
    Nov 8 at 21:03










  • You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
    – Cary Swoveland
    Nov 8 at 21:04




















  • The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
    – Cary Swoveland
    Nov 8 at 21:03










  • You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
    – Cary Swoveland
    Nov 8 at 21:04


















The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
– Cary Swoveland
Nov 8 at 21:03




The method booklist returns the hash, so you can get it as follows: b = Book.new("Treasure Island", "Bob Stevenson",...); h = b.booklist. You may then add a key-value pair: h[key] = value. This has nothing to do with the file in which you save your code (unless you want to edit the file to add the key-value pair, which I don't think is your intent
– Cary Swoveland
Nov 8 at 21:03












You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
– Cary Swoveland
Nov 8 at 21:04






You'll generate more interest in your SO questions if you state your actual question at the beginning, not at the end after laying down a lot of code. The initial statement may not be complete but it at least gives the reader an idea of what follows. Without that the reader doesn't know what aspects of the code to focus on. Also, you should pair down your code to the essentials. For example, there's no reason for the hash to contain more than, say, two keys, or for initialize to have so many arguments.
– Cary Swoveland
Nov 8 at 21:04














1 Answer
1






active

oldest

votes

















up vote
0
down vote













Changing the booklist method to this will solve your immediate problem:



  def booklist
@booklist ||= {
:Title => @title.split(/ |_|-/).map(&:capitalize).join(" "),
:Author => @author.split(/ |_|-/).map(&:capitalize).join(" "),
:Language => @language.capitalize,
:Classification => @classification,
:ISBN => @isbn.to_s,
:Book_ID => @book_id.to_s,
:Status => @borrow_status,
}
end


Now you can do booklist[:Xyz] = 'xyz'.



The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between @isbn, isbn, $isbn, ISBN, or @@isbn, etc.



There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53213488%2fhow-can-i-add-a-key-value-pair-to-a-hash-without-name%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Changing the booklist method to this will solve your immediate problem:



      def booklist
    @booklist ||= {
    :Title => @title.split(/ |_|-/).map(&:capitalize).join(" "),
    :Author => @author.split(/ |_|-/).map(&:capitalize).join(" "),
    :Language => @language.capitalize,
    :Classification => @classification,
    :ISBN => @isbn.to_s,
    :Book_ID => @book_id.to_s,
    :Status => @borrow_status,
    }
    end


    Now you can do booklist[:Xyz] = 'xyz'.



    The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between @isbn, isbn, $isbn, ISBN, or @@isbn, etc.



    There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.






    share|improve this answer

























      up vote
      0
      down vote













      Changing the booklist method to this will solve your immediate problem:



        def booklist
      @booklist ||= {
      :Title => @title.split(/ |_|-/).map(&:capitalize).join(" "),
      :Author => @author.split(/ |_|-/).map(&:capitalize).join(" "),
      :Language => @language.capitalize,
      :Classification => @classification,
      :ISBN => @isbn.to_s,
      :Book_ID => @book_id.to_s,
      :Status => @borrow_status,
      }
      end


      Now you can do booklist[:Xyz] = 'xyz'.



      The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between @isbn, isbn, $isbn, ISBN, or @@isbn, etc.



      There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Changing the booklist method to this will solve your immediate problem:



          def booklist
        @booklist ||= {
        :Title => @title.split(/ |_|-/).map(&:capitalize).join(" "),
        :Author => @author.split(/ |_|-/).map(&:capitalize).join(" "),
        :Language => @language.capitalize,
        :Classification => @classification,
        :ISBN => @isbn.to_s,
        :Book_ID => @book_id.to_s,
        :Status => @borrow_status,
        }
        end


        Now you can do booklist[:Xyz] = 'xyz'.



        The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between @isbn, isbn, $isbn, ISBN, or @@isbn, etc.



        There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.






        share|improve this answer












        Changing the booklist method to this will solve your immediate problem:



          def booklist
        @booklist ||= {
        :Title => @title.split(/ |_|-/).map(&:capitalize).join(" "),
        :Author => @author.split(/ |_|-/).map(&:capitalize).join(" "),
        :Language => @language.capitalize,
        :Classification => @classification,
        :ISBN => @isbn.to_s,
        :Book_ID => @book_id.to_s,
        :Status => @borrow_status,
        }
        end


        Now you can do booklist[:Xyz] = 'xyz'.



        The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between @isbn, isbn, $isbn, ISBN, or @@isbn, etc.



        There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 7:47









        Kimmo Lehto

        3,76611228




        3,76611228






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53213488%2fhow-can-i-add-a-key-value-pair-to-a-hash-without-name%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)