# (Ruby Version) Rotate the linked list to the right of k places

I saw this question the other day (javascript – rotate the linked list to the right of k places) and I tried to implement it in Ruby in one way totally different. Here is the code (I also created a REPL if you want to test it – https://repl.it/repls/PrimeSomeBlock):

node.rb

``````Node class
attr_accessor: value ,: next_node

def initialize (value:, next_node: nil)
@value = value
@next_node = next_node
end
end
``````

``````LinkedList class

def initialize (nodes: [])
@ nodes = nodes
end

def turning (k)
self.class.new (nodes: rotate_nodes (k))
end

def turn! (K)
@ nodes = turns_noeuds (k)
end

def to_s
@ nodes.map {| node | node.value} .join ("->")
end

private

def rotate_nodes (k)
if! k.between? (1, @ nodes.length) || ! k.is_a? (Integer)
"k" must be an integer between 1 and the length of the list "
end

@ nodes.map do | node |
n = @ nodes.find_index (node)
@ nodes[n - k].next_node = n - k == 1? nil: @nodes[n - k + 1]
@ nodes[n - k]
end
end
end
``````

main.rb

``````require_relative "./node"

n4 = Node.new (value: 5)
n3 = Node.new (value: 3, next node: n4)
n2 = Node.new (value: 7, next node: n3)
n1 = Node.new (value: 7, next node: n2)

nodes: [n1, n2, n3, n4]
)

puts << ~ HEREDOC
Rotation # {linked_list1.to_s} of 2 places.

heredoc

n9 = Node.new (value: 5)
n8 = Node.new (value: 4, next node: n9)
n7 = Node.new (value: 3, next node: n8)
n6 = Node.new (value: 2, next node: n7)
n5 = Node.new (value: 1, next node: n6)

nodes: [n5, n6, n7, n8, n9]
)

puts << ~ HEREDOC
Rotation # {linked_list2.to_s} of 3 places.
heredoc
``````

Thoughts?