I am trying to run simple shell commands in my script, but am unable to get rid of new lines even using chomp or chop.
Is there something I am missing ?
u=`echo '#{l}' | cut -d: -f4`.chop()
p2=`echo '#{l}' | cut -d: -f3`.chop()
p1=`echo '#{l}' | cut -d: -f2`.chop()
h=`echo '#{l}' | cut -d: -f1`.chop()
# **Cant get newlines to go after p1 and p2 !! ??**
path="#{p1}/server/#{p2}abc"
puts path
Output:
/usr (p1)
/server
/bin (p2) abc
Expected Output:
/usr/server/binabc
Any suggestions ?
As per some suggestions, changed my code to :
h, p1, p2, u = l.split /:/
u.strip
u.chomp
puts u.inspect
Output: "string\n"
Basically I had tried using chomp before and was hitting the same problem. Do I need to call chomp in a different way or add any gem ?
Use either
String#stripto remove all wrapping whitespace, orString#chomp(note the ‘m’) to remove a single trailing newline only.String#chopremoves the last character (or\r\npair) which could be dangerous if the command does not always end with a newline.I assume that your code did not work because the results had multiple newlines\whitespace at the end of the output. (And if so,
stripwill work for you.) You can verify this, however, by removing the call tochop, and then usingp uorputs u.inspectto see what characters are actually in the output.And for your information, it’s idiomatic in Ruby to omit parentheses when calling methods that take no arguments, e.g.
u = foo.chop.