Is it possible to concatenate Array ['a', 'b', 'c'] to String "a, b and c" ?
But ['a', 'b'] should transform to "a and b".
Rails provides a to_sentence helper:
> ['a', 'b'].to_sentence
=> "a and b"
> ['a', 'b', 'c'].to_sentence
=> "a, b, and c"
If you want a, b and c rather than a, b, and c you can change the last_word_connector:
> ['a', 'b', 'c'].to_sentence(last_word_connector: " and ")
=> "a, b and c"
a = %w{ a b }
str = a[0..-3].each_with_object("") do |item, res|
res << "#{item}, "
res
end
str << "#{a[-2]} and #{a[-1]}"
p str
a = ['a', 'b', 'c']
result = a[0...-1].join ', '
result += " and #{a[-1]}" if a.length > 1
result # => a, b and C
a = ['a', 'b']
result = a[0...-1].join ', '
result += " and #{a[-1]}" if a.length > 1
result # => a and b
Related
How to remove elements from a list untill the last element of the list
for example:
['a', 'b', 'c', 'd']
with
list.removeRange(1, ??)
wóuld evolve in
['a', 'b']
List.length is not just a getter; it's also a setter, and it can be used to truncate a List (or to grow one with nullable elements):
void main() {
var list = ['a', 'b', 'c', 'd'];
list.length = 2;
print(list); // Prints: [a, b]
}
From the documentation you can see:
A range from start to end is valid if 0 ≤ start ≤ end ≤ length.
So you can use the list's length property:
On your example:
final list = ['a', 'b', 'c', 'd'];
list.removeRange(2, list.length);
print(list); // prints [a, b]
You can test it through DartPad here.
I have an array in Ruby
words = ["horses", "follow", "useful", "offset"]
Reference:
h o r s e s
f o l l o w
u s e f u l
o f f s e t
I want to get a list of all its diagonals like this.
Here is want I expect in result:
["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]
Would be helpful if anyone can help me a bit on this. Thanks
Try that:
words = ["horses", "follow", "useful", "offset"]
words.reverse.each_with_index.map{|s,i| " " * i + s }.inject(Array.new(words.size + words.last.size-1,"")) do |a,s|
s.chars.each_with_index do |c,i|
a[i] = c + a[i]
end
a
end.map(&:strip)
# => ["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]
At first words.reverse.each_with_index.map{|s,i| " " * i + s } builds array with whitespace offset:
offset
useful
follow
horses
Inject creates array of empty strings and inside main block each string chars are prepended to proper array element
Say
string = "Johnny be good! And smile :-) "
Is there a difference between
string.gsub(/\s+/, '')
and
string.strip
?
If so, what is it?
strip only removes leading and trailing whitespace, using gsub in the way that you outline in your question will remove all whitespace from the string.
irb(main):004:0* " hello ".strip
=> "hello"
irb(main):005:0> " h e l l o ".strip
=> "h e l l o"
irb(main):006:0> " hello ".gsub(/\s+/, '')
=> "hello"
irb(main):007:0> " h e l l o ".gsub(/\s+/, '')
=> "hello"
I try to remove 1 whitespace from this string:
m y r e a l n a m e i s d o n a l d d u c k
Expected result:
my real name is donald duck
My code are:
def solve_cipher(input)
input.split('').map { |c| (c.ord - 3).chr }.join(' ') # <- Here I tried everything
end
puts solve_cipher('p| uhdo qdph lv grqdog gxfn')
# => m y r e a l n a m e i s d o n a l d d u c k
I tried everything to solve my problem, example:
input.....join(' ').squeeze(" ").strip # => m y r e a l n a m e...
or
input.....join.gsub(' ','') # => myrealnameisdonaldduck
or
input.....join(' ').lstrip # => m y r e a l n a m e...
and so on...
Well, you could split the string into words first, then split each word into characters. Using the same method you used in your code, it could look like this.
def solve_cipher(input) input.split(' ').map{ |w| w.split('').map { |c| (c.ord - 3).chr}.join('')}.join(' ') end
When joining the characters in the same word, we put no space between them; when joining the words together we put one space between them.
As stated in the question, you are using Rails, so you can also try squish method:
def solve_cipher( input )
input.split(' ').map(&:squish).join(' ')
end
str = "m y r e a l n a m e i s d o n a l d d u c k"
str.gsub(/\s(?!\s)/,'')
#=> "my real name is donald duck"
The regex matches a whitespace character not followed by another whitespace character and replaces the matched characters with empty strings. (?!\s) is a negative lookahead that matches a whitespace.
If more than two spaces may be present between words, first replace three or more spaces with two spaces, as follows.
str = "m y r e a l n a m e i s d o n a l d d u c k"
str.gsub(/\s{3,}/, " ").gsub(/\s(?!\s)/,'')
#=> "my real name is donald duck"
I know that it is not a fancy way of doing it but you could just try to create a new string and have a function traversal(input) with a counter initiated at 0, that would return this new string.
It would go through your input (which is here your string) and if the counter is 0 and it sees a space it just ignores it, increments a counter and go to the next character of the string.
If the counter is different of 0 and it sees a space it just concatenates it to the new string.
And if the counter is different of 0 and it sees something different of a space, it concatenates it to the new string and counter equals 0 again.
The trick is to use a capture group
"m y r e a l n a m e i s d o n a l d d u c k".gsub(/(\s)(.)/, '\2')
=> "my real name is donald duck
I tried the following code in Lua. The first four cases work well but the last two fail. I get nil as results in those two. What is the problem?
v = {nil, 10, nil}
a, b, c = unpack(v)
-- Output: a, b, c = nil 10 nil
print('a, b, c = ', a, b, c)
v = {nil, nil, 10}
a, b, c = unpack(v)
-- Output: a, b, c = nil nil 10
print('a, b, c = ', a, b, c)
v = {}
v[2] = 10
a, b, c = unpack(v)
-- Output: a, b, c = nil 10 nil
print('a, b, c = ', a, b, c)
v = {}
v[1] = nil
v[2] = 10
v[3] = nil
a, b, c = unpack(v)
-- Output: a, b, c = nil 10 nil
print('a, b, c = ', a, b, c)
v = {}
v[3] = 10
a, b, c = unpack(v)
-- Output: a, b, c = nil nil nil
print('a, b, c = ', a, b, c)
v = {}
v[1] = nil
v[2] = nil
v[3] = 10
a, b, c = unpack(v)
-- Output: a, b, c = nil nil nil
print('a, b, c = ', a, b, c)
When using a table as an array, all elements are required to have values different than nil.
Setting the value for a key to nil effectively removes that key from the table. But in an array all integer keys from 1 to the length of that array must be set. “Holes” are not allowed. So the behaviour in all your cases is unspecified.
You can verify by printing all key/value pairs in the table:
t = {0, nil, 2, 3}
print("pairs:")
for k, v in pairs(t) do
print("["..k.."]", v)
end
And note how ipairs breaks, since it stops at the first nil element.
print("ipairs:")
for k, v in ipairs(t) do
print("["..k.."]", v)
end
Workaround in your case is described in an answer here: Lua unpack bug?