Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby undefined method error p= method doesnt exit

Tags:

ruby

The following is a Circular double LL implementation in ruby.I am very new to ruby(less than a few days) so i had make a complicated structure for node. Removing the line

temp.n.p=temp2 

makes the error go away but otherwise it encounters the following error:-

/home/ghost/Desktop/ruby/ds/test.rb:40:in `insert': undefined method `p=' for #<Cdll:0x000000022bfde8> (NoMethodError)
    from /home/ghost/Desktop/ruby/ds/test.rb:60:in `<main>'

Here is the entire code :-

class Node
    def initialize(a,b,c)
        @data=a
        @next=b
        @prev=c
    end
    def d=(ele)
        @data=ele
    end
    def n=(ele)
        @next=ele
    end
    def p=(ele)
        @prev=ele
    end
    def d
        @data
    end
    def p
        @prev
    end
    def n
        @next
    end


end

class Cdll
    def initialize
        @sentinel=Node.new(nil,self,self)
    end

    def insert(ele)
        temp=@sentinel
        while temp.d!=nil
            temp=temp.n
        end
            temp2=Node.new(ele,temp,temp.n)
            temp.n .p=temp2
            temp.n=temp2
    end


    def search(ele)
        [email protected]
        while temp.d!=nil
            if(temp.d==ele)
                return temp
            else
                temp=temp.n
            end
        end
        return nil
    end
end


c=Cdll.new
c.insert(12)
c.insert(14)
if((x=c.search(14))!=nil)
    puts x.d
end

Any help is appreciated.

like image 288
Sr1n4th Avatar asked Jun 02 '26 08:06

Sr1n4th


1 Answers

Look at Cdll insert method.

 def insert(ele)
   temp=@sentinel
   # @sentinel.n == self 
   # => true
   while temp.d!=nil
     temp=temp.n
   end
   temp2=Node.new(ele,temp,temp.n)
   # temp.n == self
   # => true
   temp.n.p=temp2
   temp.n=temp2
 end

When you creating new instance of Cdll class - you also create an instance of Node, where previous and next element is instance of Cdll (not Node, where method p= exists).

I think it's not actually double linked list. Perhaps prev and next elements in node should be also a Node instance

like image 144
railscard Avatar answered Jun 04 '26 02:06

railscard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!