This question already has answers here:
What does <<-CONSTANT do?
(3 answers)
Closed 6 years ago.
Just found this piece of code in a Google Ruby API client on Github.
NOT_FOUND_ERROR = <<END
Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials
for more information
END
I never saw it and tested it in the console:
>> NOT_FOUND_ERROR = <<END
blabla
END
=> "blabla\n"
So basically it is a weird way to create a string? What's the motivation for using this syntax rather than NOT_FOUND_ERROR = "blabla\n" ?
EDIT: As this question was marked with "possible duplicate" I want to explain why it is not just a dup. The question that is a possible duplicate simply asks what a certain ruby script does. This Ruby script also includes the <<ABC syntax and this obviously is the core of the question, but it is not really helpful because it is hard to find. Besides that, I am going further and ask for the motivation to use this notation over creating a normal string.
It is HEREDOC. You can read more about it here(wiki) and here(Ruby instances). Usually heredocs used for more readability of multiline text.
Related
This question already has answers here:
Do I need to indent my code in Ruby?
(3 answers)
Closed 7 years ago.
I got some errors in Ruby on Rails' code, but I don't know if that's because it's not indented. Does Ruby code work without indentation?
With a project that's strictly Ruby, your indentation will not matter. Here's a SO answer to the same question that has a good example of functioning Ruby code with poor indentation. If you're curious about proper indentation style in general, Github's Ruby style guide will be a good reference for you.
Since you mentioned Rails specifically, I imagine you might be running into errors with your template code. If you're using a template like slim or jade (your views will have .slim or .jade or .haml), indentation can be important, and the lack of indentation can cause errors. For example,
h1 Example code
- #foos.each do |foo|
p = foo
Is valid slim code, but
h1 Example code
- #foos.each do |foo|
p = foo
will generate a syntax error.
As #sawa says, indentation is not obligatory but it is good practice as it allows your code to be much easier to read (for humans), which means it's far easier to catch any errors. According to the book Eloquent Ruby a sensible practice is to use two spaces per line for indentation since this is clearly an indent, but without using up too much room on the line. The book also advises not to use tabs since there is no universal length of a tab, so they can vary in length greatly. To see all this in action...
Code without indentation:
class Human
def laugh
puts "laugh"
end
def cry
puts "cry"
end
The code isn't quite right, but it's not immediately obvious where the error is.
Code with indentation and sensible spacing:
class Human
def laugh
puts "laugh"
end
def cry
puts "cry"
end
Here it's much easier to see that the end that should be aligned with the class opening is missing. In short, yes indent your code and also use sensible spacing (such as the space between the methods). It'll help you and any humans working with or reading your code.
Indentation isn't as strict as it is in python. Your code should work fine if indentation is off, but may not be maintainable or readable to another developer.
This question already has answers here:
Pretty-print for shell script
(4 answers)
Closed 7 years ago.
Talking about good coding practices. My code is getting bigger and bigger and I want to check if all my "if", and "for" loops are properly written.
I think the proper word for that is indentation (thanks #tgo).
So I have this:
if(cond1 = cond2)
if(cond3=cond4)
bla
fi
fi
but I want the following:
if(cond1 = cond2)
if(cond3=cond4)
bla
fi
fi
But for instance using Sublimetext I cannot see it like this. So repeating the question, is there any tool, software or something that can help me with this?
update: Sublime text has an option for this. (Edit-> line-> Indent) I couldn't add this to the answer.
I use vim for all my code editting (and I write a lot of bash scripts) and it has smart indenting that defaults to normal, ok stuff for all the languages I use. If you have smart indenting turned on and copy and paste code from your first block into vim (properly set up with filetype=sh), it'll turn out like your second block.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The other day I answered a question where it was necessary to loop through all the sub-dictionaries in a given directory.
As a self-taught bash user I quickly answered the question. However, in my answer I used for DIR in $(find ...); do "something"; done to loop through the sub-directories. A polite bash guru pointed out that if I continue with bad habits like that will one day find myself in a lot of trouble.
While correcting my answer I found that I had (embarrassingly) many more bad habits. I could not find any topic like this on stackoverflow, but I am sure there are many people like me at a "beginner(++)" level with bad habits based on methods that "sort-of-works".
My question is generic albeit simple:
What are important/damaging pitfalls to avoid for someone who is using bash? (If you find the question to generic to answer I would appreciate a short description of the case with link to documentation or another SO question regarding the subject is appreciated.)
E.g. When performing loops to edit files/dirs, using globb characters, pipes, logicals, short hand notation (i.e. ``) and last but not least applying functions for purposes which they should not be used.
I found Google's Styleguide very instructive. I changed some old habits after reading it, and it has a lot of examples.
EDIT: Some points to watch beneath.
Working with variables: set value without $ and access with $
Avoid confusion by using ${..} when using the variable
Calling a command within your commandline with $()
The old syntax `` will work but you can make easy mistakes.
Avoid arrays
You normally do not really need them and they have a more difficult syntax
Start (first line) your script with #!/bin/bash
It will check and use bash when available and give an error when it is missing.
Learn regex
sed can become your close friend. Even when you only use -e 's/.../.../g'
Also other utilities use regex.
Use the case statement when checking against different possible values
Avoid too much if-then-else nesting
Do not skip the if keyword when testing with [[ .. ]]
The if statement is obsolete but easier to read
Do not use eval
When you finally understand the syntax you wil learn it is dangereous.
Shell builtin's are faster but more difficult to read
basename is a simple utility but slower than ${fullfile##*/}
Maybe you should store a note with some handy builtins somewhere.
Downwards compatible?
When you think your scripts might have to be migrated to Solaris/AIX with ksh someday, try avoiding bash-specific syntax and Linux utilities. That would be quite difficult (the -i flag in sed, additional options in find) so getting bash installed on Solaris/AIX might be a better way.
Question: E.g. When performing loops to edit files/dirs, using globb characters, pipes, logicals, short hand notation (i.e. ``) and last but not least applying functions for purposes which they should not be used.
When you have a lot of scripts using the same functions, store the functions in a file like common.h
Include this file with . common.h
Learn the difference between function xxx {..} and xxx() {..}
Use local var's and return values by stdout or the returnvalue
This question already has answers here:
Why use symbols as hash keys in Ruby?
(4 answers)
Closed 8 years ago.
so writing hashes are straightforward, and it goes a little something like this...
hash = { 'x'=>1, 'y'=>2, 'z'=>3 }
but there is another way to do so...
hash_new[:x,1,:y,2,:z,3]
So my question is how are the ":x, :y, :z" elements recognized? Are they strings? And under what circumstances is the second method preferred?
Your second example doesn't actually work. The correct syntax is:
Hash[:x,1,:y,2,:z,3]
The two examples are also actually different. The first has strings as keys; the second uses symbols.
For more information on what symbols are, see "Ruby Symbols", "The Ruby_Newbie Guide to Symbols", "The Difference Between Ruby Symbols and Strings" or Ruby's documentation on the Symbol class. (For even more information, simply do a Google search for "ruby symbol")
This question already has answers here:
What is the difference between "if" statements with "then" at the end?
(5 answers)
Closed 8 years ago.
In Ruby, I know that control flow statements typically follow the following pattern.
If statement
do something
else
do something else
end
From my experiences that was the only pattern I noticed. However, when looking at code on a website, I saw something new that looked similar (if-then). I've never seen that before and would appreciate any explanations.
if statement then
do something
else
do something else
end
I'd like to know what the difference between those code blocks is. They seem to do the same thing.
Edit: I would like to clarify, I'm talking about an if then line followed by a block, not if then on one line. Please keep that in mind
The "then" syntax is used when you want to use the "if" expression on one line. In this case there needs to be a separator to ensure the line is understood by the interpreter.
See here Ruby If Syntax