I have the array:
example = ['foo', 'bar', 'quux']
I want to iterate over it and print it so it comes out like: foo bar quux, not ['foo', 'bar', 'quux'] which would be the case if I used each or for.
Note: I can't just do: example[0];example[1], etc. because the length of the array is variable.
How do I do this?
Here:
puts array.join(' ') # The string contains one space
example.join(" ") #=> foo bar quux.
If you used each to print, it would work fine:
example.each {|item| print item; print " " } #=> foo bar quux
However, if what you want is a string with the items separated by spaces, that's what the join method is for:
example.join(' ') #=> "foo bar quux"
I suspect your problem is that you're confusing printing with iterating, as each just returns the original array — if you want things printed inside of it, you need to actually print like I did in the example above.
if they may be printed underneath each other just use
puts example
=>
foo
bar
quux
otherwise use the solutions from the other answers
puts example.join(" ")
Related
I want to make it like in Python, 4 example:
print(
foobar,
footree,
foodrink
)
and it will be print in one line:
>>> "foobar, footree, foodrink"
In Ruby with the same code:
puts foobar,
footree,
foodrink
>>> "foobar"
... "footree"
... "foodrink"
Yes, I can do it with print, like this, but it looks ugly:
puts "foobar" +
"foobar" +
"foobar" +
>>> "foobar, footree, foodrink"
Thx in advance!
Edited. Now I have the following "Align the arguments of a method call if they span more than one line" and in terminal it output from a new line, I need it in one line.
You have to do
puts "#{foobar}, #{footree}, \
#{foodrink}"
>> a, b = "bar", "tree"
>> puts [a, b].join(", ")
bar, tree
or print:
>> print a, ", ", b, "\n"
bar, tree
I'm making some assumptions about your various data types based on limited information given in your example, but the closest syntax I can come up with is using an array([]) along with p and join like so:
foobar = "foobar"
footree = "footree"
foodrink = "foodrink"
p [
foobar,
footree,
foodrink
].join(" ")
#=> "foobar footree foodrink"
I've justed started learning to code in Ruby and have hit a snag in my first script. The idea is to translate the English alphabet into morse code.
I have set up a hash for my letters and their corresponding values:
morse_code = {
'a' => '.-',
'b' => '-...',
etc etc
I use the following to iterate through the hash and pull the corresponding values based on input then output it:
print "What would you like to translate: "
code = gets.strip.downcase
morse_code.each do |morse, alpha|
code.gsub!( morse, alpha )
end
puts code
The problem is that my output does not contain spacing so looks like this:
......-...-..----
instead of what I want:
.... . .-.. .-.. --- -
All I've found thus far are relating to adding a whitespace when calling variables inside a string. Below is an example:
Putting space between the output of defined variables in Ruby
Any help on how I can achieve this with my current code or rewrite it accordingly would be appreciated.
What you need is to take the input and map its characters to corresponding values from the morse_code hash, and then join it with spaces:
code = 'abb'
code.each_char.map { |letter| morse_code[letter] }.join(' ')
#=> ".- -... -..."
Reference:
String#each_char
Enumerable#map
Array#join
EDIT:
To make your initial code to work the only thing you lacked is a space, which is easy to add using interpolation:
code = 'abab'
morse_code.each do |morse, alpha|
code.gsub!(morse, "#{alpha} ") # <=============
end
code
#=> ".- -... .- -... "
code.rstrip
#=> ".- -... .- -..."
If you did not know about interpolation - here is how it works:
foo = 'bar'
"#{foo}" #=> "bar"
"hello I am #{foo}" #=> "hello I am bar"
So going back to your case, all the following does
"#{alpha} "
is adding a space after, which you needed. Problem with it, that the resulting string will have an extra space at the end, which we solved with
code.rstrip
I know I can easily remove a substring from a string.
Now I need to remove every substring from a string, if the substring is in an array.
arr = ["1. foo", "2. bar"]
string = "Only delete the 1. foo and the 2. bar"
# some awesome function
string = string.replace_if_in?(arr, '')
# desired output => "Only delete the and the"
All of the functions to remove adjust a string, such as sub, gsub, tr, ... only take one word as an argument, not an array. But my array has over 20 elements, so I need a better way than using sub 20 times.
Sadly it's not only about removing words, rather about removing the whole substring as 1. foo
How would I attempt this?
You can use gsub which accepts a regex, and combine it with Regexp.union:
string.gsub(Regexp.union(arr), '')
# => "Only delete the and the "
Like follows:
arr = ["1. foo", "2. bar"]
string = "Only delete the 1. foo and the 2. bar"
arr.each {|x| string.slice!(x) }
string # => "Only delete the and the "
One extended thing, this also allows you to crop text with regexp service chars like \, or . (Uri's answer also allows):
string = "Only delete the 1. foo and the 2. bar and \\...."
arr = ["1. foo", "2. bar", "\..."]
arr.each {|x| string.slice!(x) }
string # => "Only delete the and the and ."
Use #gsub with #join on the array elements
You can use #gsub by calling #join on the elements of the array, joining them with the regex alternation operator. For example:
arr = ["foo", "bar"]
string = "Only delete the foo and the bar"
string.gsub /#{arr.join ?|}/, ''
#=> "Only delete the and the "
You can then deal with the extra spaces left behind in any way you see fit. This is a better method when you want to censor words. For example:
string.gsub /#{arr.join ?|}/, '<bleep>'
#=> "Only delete the <bleep> and the <bleep>"
On the other hand, split/reject/join might be a better method chain if you need to care about whitespace. There's always more than one way to do something, and your mileage may vary.
Okay, so I'm building something that takes a text file and breaks it up into multiple sections that are further divided into entries, and then puts <a> tags around part of each entry. I have an instance variable, #section_name, that I need to use in making the link. The problem is, #section_name seems to lose its value if I look at it wrong. Some code:
def find_entries
#sections.each do |section|
#entries = section.to_s.shatter(/(some) RegEx/)
#section_name = $1.to_s
puts #section_name
add_links
end
end
def add_links
puts "looking for #{#section_name} in #{#section_hash}"
section_link = #section_hash.fetch(#section_name)
end
If I comment out the call to add_links, it spits out the names of all the sections, but if I include it, I just get:
looking for in {"contents" => "of", "the" => "hash"}
Any help is much appreciated!
$1 is a global variable which can be used in later code.$n contains the n-th (...) capture of the last match
"foobar".sub(/foo(.*)/, '\1\1')
puts "The matching word was #{$1}" #=> The matching word was bar
"123 456 789" =~ /(\d\d)(\d)/
p [$1, $2] #=> ["12", "3"]
So I think #entries = section.to_s.shatter(/(some) RegEx/) line is not doing match properly. thus your first matched group contains nothing. so $1 prints nil.
Is there a shorter way of doing the following?
foo =
config.include?(:bar) ?
"#{bar}.baz" :
"baz"
I'm looking for a readable one-liner that appends a variable, plus a delimiter, if the variable exists (assuming it's a string).
config is a Hash.
You could do this:
foo = [bar, 'baz'].compact.join('.')
If bar is nil then compact will remove it from the array and delimiter won't be added.
foo = "#{"bar." if config.include?(:bar)}baz"