简体   繁体   中英

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

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]

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM