Jaron787
Jaron787

Reputation: 560

Ruby - get nth Character from string

I am trying to get the 5th to 7th Character from #{vm} however I can't seem to get it to work. What am I missing?

puts "#{Colorable.wrap_color("Restarting VM's", :BLUE)}"
change_set.vms_to_restart.each do |vm|

puts "JH 0 - " + %x{hostname}
host_code = %x{hostname}[7,9]
vm_code   = #vm[5,7]   <---- THIS DOES NOT WORK

puts "JH 1 - #{host_code}"
puts "JH 2 - #{vm_code}"
puts "JH 3 - #{vm}"

  puts "Restarting ... #{vm}"
exit 1
  vm.restart
end
puts " "

Output:

Restarting VM's
JH 0 - qdscild401
JH 1 - 401
JH 2 -                    <---------- BLANK
JH 3 - qdcld401.vm10
Restarting ... qdcld401.vm10

Upvotes: 0

Views: 3181

Answers (3)

SteveTurczyn
SteveTurczyn

Reputation: 36860

Just to clarify, vm[5,7] means get the sixth character and the six additional characters after it (for a total of seven characters).

So

vm = 'abcdefghijklmno'
vm[5,7]
=> 'fghijkl'

If you only want the FIFTH character to the SEVENTH character

vm[4,3]
=> 'efg'

Upvotes: 5

Jaron787
Jaron787

Reputation: 560

Ah nice - I tried

vm_code   = vm.to_s[5,7]

But it hasn't trimmed off everything after the 7th Character

Restarting VM's
JH 0 - qdscild401
JH 1 - 401 
JH 2 - 401.vm1          <----- NOT TRIMMED after 7th
JH 3 - qdcld401.vm10
Restarting ... qdcld401.vm10

Upvotes: 1

ReggieB
ReggieB

Reputation: 8212

In this code:

vm_code   = #vm[5,7]

everything after the # is a comment. Therefore, that statement is effectively:

vm_code = nil

The line should be

vm_code   = vm[5,7]

Or if the vm object is not a String you could try

vm_code   = vm.to_s[5,7]

Upvotes: 3

Related Questions